我有一个看起来像这样的列表:
[['0', '0', '254', '0', 'R'], ['0', '97', '0', '65', 'R'], ['0', '98', '0', '66', 'R'], []]
[a,b,c,d,e]
格式
我想做的是制作一个字典,使(a,b) : (c,d,e)
rules = dict(((a, b), (c, d, e))
for (a, b, c, d, e) in rules)
我得到的错误是:
ValueError:没有足够的值可解包(预期5,得到0)
我猜我的问题是格式化输入字符串,因为它没有将其读取为元组。
我想做的是在列表中以元组的形式读取,并提取每组中的5个值作为字典的a,b,c,d,e值
答案 0 :(得分:1)
如何检查尺寸是否为5?
l = [
['0', '0', '254', '0', 'R'],
['0', '97', '0', '65', 'R'],
['0', '98', '0', '66', 'R'],
[]
]
out = {(x[0],x[1]):(x[2],x[3],x[4]) for x in l if len(x) == 5} # or just if x
print(out)
或感谢@Jon Clements
out = {tuple(x[:2]):x[2:] for x in l if x}
返回:
{('0', '0'): ('254', '0', 'R'),
('0', '97'): ('0', '65', 'R'),
('0', '98'): ('0', '66', 'R')}
答案 1 :(得分:1)
您可以将filter与字典理解结合使用:
data = [['0', '0', '254', '0', 'R'], ['0', '97', '0', '65', 'R'], ['0', '98', '0', '66', 'R'], []]
result = {(a, b): (c, d, e) for a, b, c, d, e in filter(None, data)}
print(result)
输出
{('0', '97'): ('0', '65', 'R'), ('0', '98'): ('0', '66', 'R'), ('0', '0'): ('254', '0', 'R')}
或更类似于您的代码:
rules = [['0', '0', '254', '0', 'R'], ['0', '97', '0', '65', 'R'], ['0', '98', '0', '66', 'R'], []]
result = dict(((a, b), (c, d, e)) for a, b, c, d, e in filter(None, rules))
print(result)
输出
{('0', '0'): ('254', '0', 'R'), ('0', '98'): ('0', '66', 'R'), ('0', '97'): ('0', '65', 'R')}