當前位置:首頁 » 編程語言 » pythonifthenelse

pythonifthenelse

發布時間: 2025-09-18 20:33:19

A. python編寫用pow()函數計算球的體積

使用鍵盤輸入值並不是編輯表中值的唯一方式。在某些情況下,為了設置欄位值,可能要對單條記錄甚至是所有記錄執行數學計算。您可以對所有記錄或選中記錄執行簡單計算和高級計算。此外,還可以在屬性表中的欄位上計算面積、長度、周長和其他幾何屬性。以下各部分包括使用欄位計算器的若干示例。使用 Python、SQL 和 Arcade 執行計算。

本主題著重於基於 Python 的計算欄位示例。要了解有關 Arcade 表達式的詳細信息,請參閱 ArcGIS Arcade 指南。要了解有關 SQL 表達式的詳細信息,請參閱計算欄位。

註:


  • Python 強制將縮進作為語法的一部分。請使用兩個或四個空格來定義每個邏輯級別。將語句塊的開頭和結尾對齊並且保持一致。

  • Python 計算表達式欄位將使用驚嘆號 (!!) 括起。

  • 命名變數時,請注意 Python 區分大小寫,因此 value 不同於 Value。

  • 輸入語句後,如果想將其寫入文件,請單擊導出。導入按鈕將提示您查找和選擇一個現有的計算文件。


  • 簡單計算

    僅通過一個短表達式就可以計算出多種計算結果。

    簡單字元串示例

    一系列 Python 字元串函數均支持使用字元串,包括 capitalize、rstrip 和 replace。

    將 CITY_NAME 欄位中字元串的首字母大寫。

    !CITY_NAME!.capitalize()

    去掉 CITY_NAME 欄位中自字元串結尾起的所有空白區。

    !CITY_NAME!.rstrip()

    將 STATE_NAME 欄位中的「california」全部替換為「California」。

    !STATE_NAME!.replace("california", "California")

    在 Python 中,字元串欄位中的字元可以通過索引和分割操作進行訪問。索引操作將在索引位置提取字元,而分割操作則會提取一組字元。在下表中,假設 !fieldname! 是值為 "abcde" 的字元串欄位。

    示例

    說明

    結果

    !fieldname![0]

    第一個字元

    "a"

    !fieldname![-2]

    倒數第二個字元

    "d"

    !fieldname![1:4]

    第二、三和四個字元

    "bcd"

    Python 也支持使用 format() 方法的字元串格式。

    將合並後的 FieldA 和 FieldB 以冒號分隔開。

    "{}:{}".format(!FieldA!, !FieldB!)

    常見 Python 字元串操作

    簡單數學示例

    Python 提供了處理數字的工具。Python 也支持一些數值和數學函數,包括 math、cmath、decimal、random、itertools、functools 和 operator。

    運算符

    說明

    示例

    結果

    x + y

    x 加上 y

    1.5 + 2.5

    4.0

    x - y

    x 減去 y

    3.3 - 2.2

    1.1

    x * y

    x 乘以 y

    2.0 * 2.2

    4.4

    x / y

    x 除以 y

    4.0 / 1.25

    3.2

    x // y

    x 除以 y(向下取整除法)

    4.0 // 1.25

    3.0

    x % y

    x 模 y

    8 % 3

    2

    -x

    x 的負數表達式

    x = 5

    -x

    -5

    +x

    x 不變

    x = 5

    +x

    5

    x ** y

    以 x 為底,以 y 為指數的冪

    2 ** 3

    8

    !Rank! * 2

    根據給定的半徑欄位計算球體的體積。

    4.0 / 3.0 * math.pi * !Radius! ** 3

    舊版本:

    在 ArcGIS Pro 中,使用的是 Python 3,在 ArcGIS Desktop 中,使用的 Python 2。Python 2 使用的是整型數學計算,這就意味著兩個整型值相除將始終生成整型值 (3 / 2 = 1)。在 Python 3 中,兩個整型值相除將生成浮點型值 (3 / 2 = 1.5)。

    Python 內置函數

    Python 包含多個可用的內置函數,包括 max、min、round 和 sum。

    Python 內置函數

    通過欄位列表計算每條記錄的最大值。

    max([!field1!, !field2!, !field3!])

    通過欄位列表計算每條記錄的總和。

    sum([!field1!, !field2!, !field3!])使用代碼塊

    通過 Python 表達式和代碼塊參數可執行以下操作:

  • 在表達式中應用任意 Python 函數。

  • 訪問地理處理函數和對象。

  • 訪問要素幾何的屬性。

  • 訪問新的隨機值運算符。

  • 使用 if-then-else 邏輯對值進行重分類。

  • 表達式類型

    代碼塊

    Python 3

    支持 Python 功能。使用 Python 函數 (def) 表示代碼塊。在適當的情況下,幾何屬性將通過地理處理對象表示(如點對象)。

    Arcade

    支持 Arcade 功能。

    SQL

    支持 SQL 表達式。

    執行 SQL 表達式可以更好地支持使用要素服務和企業級地理資料庫的計算,尤其是在性能方面。使用該表達式可以將單次請求設置為要素服務或資料庫,而不必一次執行一個要素或一行的計算。

    舊版本:

    在 ArcGIS Desktop 中,計算欄位工具支持 VB、PYTHON 和 PYTHON_9.3 表達式類型。VB 表達式類型,在某些產品中受支持,但在 64 位產品中不受支持,其中包括 ArcGIS Pro。

    出於相後兼容性考量,ArcGIS Pro 中仍然支持 PYTHON 和 PYTHON_9.3 關鍵字,但是不會作為選擇列出。使用這些關鍵字的 Python 腳本將可繼續使用。

    Python 3 表達式類型與舊版 PYTHON_9.3 關鍵字的唯一區別在於 Python 3 會將日期欄位中的值作為 Python datetime 對象返回。

    註:

    Python 3 表達式類型與隨 ArcGIS Pro 安裝的 Python 版本無關。這只是歷史上的第三個 Python 相關關鍵字(繼 PYTHON 和 PYTHON_9.3 之後。

    各 Python 函數可通過 def 關鍵字定義,關鍵字後為函數名稱及函數的輸入參數。可編寫 Python 函數,使 Python 函數能夠接受任何數量的輸入參數(也可以沒有任何參數)。函數將通過 return 語句返回值。函數名稱可由您自行選取(不得使用空格,也不得以數字開頭)。

    註:

    如果函數未通過 return 語句顯式返回值,則函數將返回 None。

    註:

    請牢記,Python 強制要求將縮進作為語法的一部分。請使用四個空格來定義每個邏輯級別。將語句塊的開頭和結尾對齊並且保持一致。

    代碼示例 - 數學

    在使用以下數學示例時,請假設表達式類型為 Python 3。

    將欄位的值四捨五入為保留兩位小數。

    表達式:
    round(!area!, 2)

    通過 math 模塊將米轉換成英尺。以轉換值為底,以 2 為指數進行冪運算,然後再乘以 area。

    表達式:
    MetersToFeet((float(!shape.area!)))
    代碼塊:
    import math
    def MetersToFeet(area):
    return math.pow(3.2808, 2) * area通過 Python 邏輯計算欄位

    可以使用 if、else 和 elif 語句將邏輯模式包含在代碼塊中。

    按照欄位值進行分類。

    表達式:
    Reclass(!WELL_YIELD!)
    代碼塊:
    def Reclass(WellYield):
    if (WellYield >= 0 and WellYield <= 10):
    return 1
    elif (WellYield > 10 and WellYield <= 20):
    return 2
    elif (WellYield > 20 and WellYield <= 30):
    return 3
    elif (WellYield > 30):
    return 4代碼實例 - 幾何

    除以下代碼示例外,請參閱下方的「幾何單位轉換」部分,以了解有關轉換幾何單位的詳細信息。

    計算某要素的面積。

    表達式:
    !shape.area!

    計算某要素的最大 x 坐標。

    表達式:
    !shape.extent.XMax!

    計算某要素中的折點數。

    表達式:
    MySub(!shape!)
    代碼塊:
    def MySub(feat):
    partnum = 0
    # Count the number of points in the current multipart feature
    partcount = feat.partCount
    pntcount = 0
    # Enter while loop for each part in the feature (if a singlepart
    # feature, this will occur only once)
    while partnum < partcount:
    part = feat.getPart(partnum)
    pnt = part.next()
    # Enter while loop for each vertex
    while pnt:
    pntcount += 1
    pnt = part.next()

    # If pnt is null, either the part is finished or there
    # is an interior ring
    if not pnt:
    pnt = part.next()
    partnum += 1
    return pntcount

    將點要素類中每個點的 x 坐標平移 100。

    表達式:
    shiftXCoordinate(!SHAPE!)
    代碼塊:
    def shiftXCoordinate(shape):
    shiftValue = 100
    point = shape.getPart(0)
    point.X += shiftValue
    return point幾何單位轉換

    幾何欄位的面積和長度屬性可通過用 @ 符號表示的單位類型進行修改。

  • 面積測量單位關鍵字:



  • ACRES | ARES | HECTARES | SQUARECENTIMETERS | SQUAREDECIMETERS | SQUAREINCHES | SQUAREFEET | SQUAREKILOMETERS | SQUAREMETERS | SQUAREMILES | SQUAREMILLIMETERS | SQUAREYARDS | SQUAREMAPUNITS | UNKNOWN

  • 線性測量單位關鍵字:



  • CENTIMETERS | DECIMALDEGREES | DECIMETERS | FEET | INCHES | KILOMETERS | METERS | MILES | MILLIMETERS | NAUTICALMILES | POINTS | UNKNOWN | YARDS

  • 註:

    如果數據存儲在地理坐標系中且具有線性單位(例如英尺),則會通過測地線演算法轉換長度計算的結果。

    警告:

    轉換地理坐標系中數據的面積單位會生成不正確的結果,這是由於沿 globe 的十進制度並不一致。

    計算某要素的長度(以碼為單位)。

    表達式:
    !shape.length@yards!

    計算某要素的面積(以英畝為單位)。

    表達式:
    !shape.area@acres!

    測地線面積和長度也可以通過帶 @(後跟測量單位關鍵字)的 geodesicArea 和 geodesicLength 屬性進行計算。

    計算某要素的測地線長度(以碼為單位)。

    表達式:
    !shape.geodesicLength@yards!

    計算某要素的測地線面積(以英畝為單位)。

    表達式:
    !shape.geodesicArea@acres!代碼實例 - 日期

    日期和時間可使用 datetime 和 time 模塊進行計算。

    計算當前日期。

    表達式:
    time.strftime("%d/%m/%Y")

    計算當前日期和時間。

    表達式:
    datetime.datetime.now()

    計算的日期為 2000 年 12 月 31 日。

    表達式:
    datetime.datetime(2000, 12, 31)

    計算當前日期和欄位中的值之間的天數。

    表達式:
    (datetime.datetime.now() - !field1!).days

    通過向欄位中的日期值添加 100 天來計算日期。

    表達式:
    !field1! + datetime.timedelta(days=100)

    計算欄位中的日期值為一周中的周幾(例如,星期天)。

    表達式:
    !field1!.strftime('%A')代碼實例 - 字元串

    可以使用多種 Python 編碼模式來完成字元串計算。

    返回最右側三個字元。

    表達式:
    !SUB_REGION![-3:]

    將所有大寫字母 P 替換為小寫字母 p。

    表達式:
    !STATE_NAME!.replace("P","p")

    通過空格分隔符串連兩個欄位。

    表達式:
    !SUB_REGION! + " " + !STATE_ABBR!轉換為正確的大小寫形式

    下列各例顯示的是轉換單詞的不同方法,這些方法可使每個單詞的首字母變為大寫、其餘字母變為小寫。

    表達式:
    ' '.join([i.capitalize() for i in !STATE_NAME!.split(' ')])表達式:
    !STATE_NAME!.title()正則表達式

    Python 的 re 模塊提供了正則表達式匹配操作,可用於對字元串執行復雜的模式匹配和替換規則。

    re - 正則表達式運算正則表達式的用法

    使用單詞 Street 替換 St 或 St.,在字元串的末尾生成一個新單詞。

    表達式:
    update_street(!ADDRESS!)
    代碼塊:
    import re
    def update_street(street_name):
    return re.sub(r"""(St|St.)""",
    'Street',
    street_name)累加計算和順序計算

    可以使用全局變數來進行累加計算和順序計算。

    根據某間隔值計算順序 ID 或數字。

    表達式:
    autoIncrement()
    代碼塊:
    rec=0
    def autoIncrement():
    global rec
    pStart = 1 # adjust start value, if req'd
    pInterval = 1 # adjust interval value, if req'd
    if (rec == 0):
    rec = pStart
    else:
    rec = rec + pInterval
    return rec

    計算數值型欄位的累加值。

    表達式:
    accumulate(!FieldA!)
    代碼塊:
    total = 0
    def accumulate(increment):
    global total
    if total:
    total += increment
    else:
    total = increment
    return total

    計算數值型欄位的百分比增量。

    表達式:
    percentIncrease(float(!FieldA!))
    代碼塊:
    lastValue = 0
    def percentIncrease(newValue):
    global lastValue
    if lastValue:
    percentage = ((newValue - lastValue) / lastValue) * 100
    else:
    percentage = 0
    lastValue = newValue
    return percentage隨機值

    可以使用 random 模塊來計算隨機值。

    通過 numpy 站點包來計算 0.0 和 1.0 之間的隨機浮點值。

    表達式:
    getRandomValue()
    代碼塊:
    import numpy
    def getRandomValue():
    return numpy.random.random()

    使用隨機模塊來計算 0 與 10 之間的隨機整數。

    表達式:
    random.randint(0, 10)
    代碼塊:
    import random計算空值

    在 Python 表達式中,可通過 Python None 來計算空值。

    註:

    僅當該欄位為空時,才可以進行以下計算。

    使用 Python None 計算空值。

    表達式:
    None相關主題

    有關欄位計算的基礎知識

    授權轉載:gisoracle

    網課學習 + 權威結業證書

    我們精心匯總了一些相對簡單

    培訓考核通過便可獲取的證書

    自然資源部職鑒中心發證

    可用於招投標、資質系統

    測繪師繼續教育20學時

    中國測繪網新媒體中心

    [email protected]

    商務合作/微信 214979525

B. python if 語句如何書寫

第三行前面應該也有三個點,怎麼沒有了,第二行結束後按的是回車么。還有對於python的子句和嵌套關系都是又空格來確定的,在命令行運行盡量用tab鍵。

如果某個子句沒有內容,那麼也不能是空的,也就是冒號:包含的塊即使沒有東西,也得寫一個pass,如果想結束子塊,在命令行下,要按兩行enter。

或者

if <條件> then <語句> ;

注意:Pascal中也有if 的嵌套,但else只承接最後一個沒有承接的if,如:

if <條件1> then if <條件2> then <語句1> else <語句2>; 此處<語句2>當且僅當<條件1>成立且<條件2>不成立時運行。

if <條件1> then begin if <條件2> then <語句1> end else <語句2>; 此處<語句2>只要<條件1>成立就運行。

C. Python里怎麼實現switch case

學習Python過程中,發現沒有switch-case,過去寫C習慣用Switch/Case語句,官方文檔說通過if-elif實現。所以不妨自己來實現Switch/Case功能。
方法一
通過字典實現
def foo(var):
return {
'a': 1,
'b': 2,
'c': 3,
}.get(var,'error') #'error'為默認返回值,可自設置

方法二
通過匿名函數實現
def foo(var,x):
return {
'a': lambda x: x+1,
'b': lambda x: x+2,
'c': lambda x: x+3,
}[var](x)

方法三
通過定義類實現
參考Brian Beck通過類來實現Swich-case
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False

def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration

def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False

# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
print 10
break
if case('eleven'):
print 11
break
if case(): # default, could also just omit condition or 'if True'
print "something else!"
# No need to break here, it'll stop anyway

# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
if case('a'): pass # only necessary if the rest of the suite is empty
if case('b'): pass
# ...
if case('y'): pass
if case('z'):
print "c is lowercase!"
break
if case('A'): pass
# ...
if case('Z'):
print "c is uppercase!"
break
if case(): # default
print "I nno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case('!', '?', '.'): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I nno what c was!"

# Since Pierre's suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.

查看Python官方:PEP 3103-A Switch/Case Statement
發現其實實現Switch Case需要被判斷的變數是可哈希的和可比較的,這與Python倡導的靈活性有沖突。在實現上,優化不好做,可能到最後最差的情況匯編出來跟If Else組是一樣的。所以Python沒有支持。

熱點內容
網頁加密代碼 發布:2025-09-18 21:56:12 瀏覽:162
安卓targz解壓 發布:2025-09-18 21:45:58 瀏覽:799
怎麼設置手機屏幕密碼怎麼設置 發布:2025-09-18 21:44:18 瀏覽:816
直線插補演算法 發布:2025-09-18 21:22:49 瀏覽:653
矩陣內的演算法 發布:2025-09-18 20:55:07 瀏覽:571
android網路優化 發布:2025-09-18 20:53:19 瀏覽:217
看交換機配置哪些是默認的 發布:2025-09-18 20:46:59 瀏覽:619
在釘釘上如何獲取自己的密碼 發布:2025-09-18 20:46:12 瀏覽:854
pythonifthenelse 發布:2025-09-18 20:33:19 瀏覽:913
熱血傳奇腳本怎麼做 發布:2025-09-18 20:29:06 瀏覽:613