Python循环:循环相同,语法不同,输出属于不同类型。为什么?

时间:2015-11-11 19:54:50

标签: python-2.7 loops

x = int

option = { 1 : 'One',
       2 : 'Two',
       3 : 'Three',
       4 : 'Four',
       5 : 'Five',
       6 : 'Six',
       7 : 'Seven',
       8 : 'Eight',
       9 : 'Nine' }

#方法1:

for a, b in option.items():
    if a == x:
        print b

# Output: Eight


# Method 2: (Is not identical?)

print [b for a, b in option.items() if a == x]

# Output: ['Eight']

这里发生了什么,如果我更喜欢方法#2的清洁形式,我怎样才能将其输出转换为简单的字符串?

1 个答案:

答案 0 :(得分:0)

虽然这适用于方法2:

print([b for a, b in option.items() if a == x][0])

我非常喜欢方法3:

print(option[x])

两者都打印:

Eight