簡體   English   中英

字典的單數或復數標識符?

[英]singular or plural identifier for a dictionary?

命名容器時,有什么更好的編碼風格:

source = {}
#...
source[record] = some_file

要么

sources = {}
#...
sources[record] = some_file

復數在創作時更自然; 任務中的單數。

這不是一個無所事事的問題; 當我不確定變量是容器還是單個值時,我確實發現自己在舊代碼中感到困惑。

UPDATE

似乎有一個普遍的共識,即當字典用作映射時,最好使用更詳細的名稱(例如, recordToSourceFilename ); 如果我絕對想要使用短名稱,那么將其復數(例如, sources )。

我認為有兩個非常具體的詞典用例應該單獨識別。 但是,在解決它們之前,應該注意字典的變量名應該幾乎總是單數,而列表應該幾乎總是復數。

  1. 字典作為類似對象的實體:有時候你有一個代表某種類似對象的數據結構的字典。 在這些實例中,字典幾乎總是引用單個類似對象的數據結構,因此應該是單數的。 例如:

      # assume that users is a list of users parsed from some JSON source # assume that each user is a dictionary, containing information about that user for user in users: print user['name'] 
  2. 字典作為映射實體:其他時候,您的字典可能表現得更像典型的哈希映射。 在這種情況下,最好使用更直接的名稱,盡管仍然是單數。 例如:

     # assume that idToUser is a dictionary mapping IDs to user objects user = idToUser['0001a'] print user.name 
  3. 列表:最后,您有列表,這是一個完全獨立的想法。 這些應該幾乎總是復數,因為它們很簡單,是其他實體的集合。 例如:

     users = [userA, userB, userC] # makes sense for user in users: print user.name # especially later, in iteration 

我確信有一些模糊的或其他不太可能的情況可能要求在這里做出一些例外,但我覺得這是一個非常強大的指南,在命名字典和列表時要遵循,不僅僅是在Python中,而是在所有語言中。

它應該是復數,因為程序的行為就像你大聲朗讀一樣。 讓我告訴你為什么它不應該是單數的(完全人為的例子):

c = Customer(name = "Tony")
c.persist()

[...]

#
# 500 LOC later, you retrieve the customer list as a mapping from
# customer ID to Customer instance.
#

# Singular
customer = fetchCustomerList()
nameOfFirstCustomer = customer[0].name
for c in customer: # obviously it's totally confusing once you iterate
    ...

# Plural
customers = fetchCustomerList()
nameOfFirstCustomer = customers[0].name    
for customer in customers: # yeah, that makes sense!!
    ...

此外,有時候最好有一個更明確的名稱,你可以從中推斷映射(對於字典)和可能的類型。 當我引入字典變量時,我通常會添加一個簡單的注釋。 一個例子:

# Customer ID => Customer
idToCustomer = {}

[...]

idToCustomer[1] = Customer(name = "Tony")

我更喜歡復數形式的容器。 使用時只有一些可以理解的邏輯:

entries = []
for entry in entries:
     #Code...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM