【问题标题】:Coverting List to Dictionary in Python在 Python 中将列表转换为字典
【发布时间】:2019-12-13 06:40:14
【问题描述】:

如何通过分别比较索引 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}

【问题讨论】:

  • 如果您知道列表中始终存在三元素,则不必使用字典理解
  • 是每个列表只有一个条目还是有['tunnel0','up,'up','tunnel1','up,'down']之类的列表?
  • TunnelStatus = {a[0]:1 if a[1]==a[2]=='up' else 0}

标签: python list-comprehension dictionary-comprehension


【解决方案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]。因此,您将在字典中收到多个输出键,所有值都相等。

【讨论】:

  • 感谢 IsaacDj 的回复。这有助于我理解我做错了什么。
  • 我的荣幸。祝你在这个主题上取得进步
【解决方案2】:

您可以使用计数器并创建一个字典列表:

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}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 2014-07-28
    • 2022-01-02
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多