簡體   English   中英

使用if條件在Python中創建鍵/值對

[英]Create key/value pair in Python using an if conditional

在Python 3.5中,是否可以使用if語句構建字典鍵/值對?

例如,給定以下if-conditional

if x == 1:
    color = 'blue'
elif x == 2:
    color = 'red'
else:
    color = 'purple'

如何創建包含此if-conditional的字典鍵/值對?

dict(
    number = 3,
    foo = 'bar',
    color = 'blue' if x == 1, 'red' if x == 2, else 'purple'
)

密鑰必須是不可變的(發音:“hash-able”)對象。 這意味着字符串,元組,整數,浮點或具有__hash__方法的任何對象。 您正在創建的詞典似乎需要這樣:

x = 2
d1 = {
    "number": 3,
    "foo": "bar",
    "color": "blue" if x == 1 else "red" if x == 2 else "purple"
}
# or:
x = 3
d2 = dict(
    number=3,
    foo="bar",
    color="blue" if x == 1 else "red" if x == 2 else "purple"
)
print(d1["color"]) # => red
print(d2["color"]) # => purple

隨着@timgeb的出現,更普遍的首選方法是使用dict.get方法,因為if-conditional語句的可讀性越來越低。

我建議不要使用條件,而是使用數字到顏色的映射。

>>> x = 2
>>> dict(
...     number = 3,
...     foo = 'bar',
...     color = {1: 'blue', 2: 'red'}.get(x, 'purple')
... )
{'color': 'red', 'foo': 'bar', 'number': 3}

如果多次使用數字 - >顏色映射,請在外部定義並為其指定名稱。

如果在字典中找不到xget將返回后備值'purple'

一點點補充。 使用if條件的解決方案可能看起來更好用一些格式(特別是如果你有很多條件):

x = 3
d1 = {
    "number": 3,
    "foo": "bar",
    "color": 
        "blue" if x == 1 else 
        "red" if x == 2 else 
        "purple"
}

暫無
暫無

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

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