用Python覆盖列表到字典

时间:2019-12-13 06:40:14

标签: python list-comprehension dictionary-comprehension

如何通过分别比较索引2和3的值将python列表转换为字典

['Tunnel0', 'up', 'up'] --> {'Tunnel0':'1'}
['Tunnel0', 'up', 'down']--> {'Tunnel0':'0'}
['Tunnel0', 'down', 'down']--> {'Tunnel0':'0'}
['Tunnel0', 'down', 'up']--> {'Tunnel0':'0'}

有什么帮助吗?

这是我尝试过的

a = ['Tunnel0', 'up', 'up']
TunnelStatus = {i:1 if a[1]==a[2] else 0 for i in a }
print(TunnelStatus)
>>>{'Tunnel0': 1, 'up': 1}

b = ['Tunnel0', 'up', 'down']
TunnelStatus = {i: 1 if b[1]==b[2] else 0 for i in b }
print(TunnelStatus)
>>>{'Tunnel0': 0, 'up': 0, 'down': 0}

3 个答案:

答案 0 :(得分:1)

对于我来说,不清楚是要为长度为3n的列表提供通用解决方案还是为3个字符串的列表提供通用解决方案。

这将在任何情况下提供解决方案:

TunnelStatus = {a[i]:1 if a[i+1] == a[i+2] == 'up' else 0 for i in range(0, len(a), 3)}

通过比较i+1i+2变量,此理解以3的跳跃次数进行迭代。

以下是一些输出:

a = ['tunnel0','up','up','tunnel1','up','down','tunnel2','down','up',
    'tunnel3','down','down']
b = ['tunnel0','up','up']

{a[i]:1 if a[i+1] == a[i+2] == 'up' else 0 for i in range(0, len(a), 3)}
>>>{'tunnel0': 1, 'tunnel1': 0, 'tunnel2': 0, 'tunnel3': 0}

{b[i]:1 if b[i+1] == b[i+2] == 'up' else 0 for i in range(0, len(b), 3)}
>>>{'tunnel0': 1}

在您的解决方案中,您将遍历整个列表并比较常量a[1]a[2]。因此,您将在字典中收到多个所有值都相等的输出键。

答案 1 :(得分:0)

您可以使用counter并创建字典列表:

from collections import Counter
s = [['Tunnel0', 'up', 'up'],
['Tunnel0', 'up', 'down'],
['Tunnel0', 'down', 'down'],
['Tunnel0', 'down', 'up']]

d=[]
for item in s:
  if Counter(item)['up'] == 2:
     d.append({item[0]: 1})
  else:
     d.append({item[0]: 0})

d

输出:

 [{'Tunnel0': 1}, {'Tunnel0': 0}, {'Tunnel0': 0}, {'Tunnel0': 0}]

答案 2 :(得分:-1)

您可以尝试以下操作:

    a = ['Tunnel0', 'up', 'up'] 
    if a[1] == 'up'
       if a[1] == a[2]:
         status = {a[0]:'1'}
    else :
         status = {a[0]:'0'}
    print(status)