[英]How to move items from a list into a dictionary
我试图将项目从列表移动到字典中,但出现以下错误:
'int'对象不可下标
这是我的代码:
l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
d = {}
for line in l_s:
if line[0] in d:
d[line[0]].append(line[1])
else:
d[line[0]] = [line[1]]
print(d)
我将如何进行更改?
为什么会出现错误?
在Python中,该错误通常表示“您无法切片该对象”。 字符串,列表,元组等是可切片的,但整数不是。 该错误会在迭代过程中引发,因为它遇到整数。
选件
根据所需的结果,可以尝试以下方法:
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5), ('six', 6)]
。 pip install more_itertools
。 解
我怀疑您想要类似选项3的结果:
import more_itertools as mit
lst = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
{k: v for k, v in mit.sliced(lst, 2)}
# {'five': 5, 'four': 4, 'one': 1, 'six': 6, 'three': 3, 'two': 2}
像这样吗
使用Way一次迭代列表中的两个项目? 和字典理解:
>> l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
>>> {k:v for k, v in zip(*[iter(l_s)]*2)}
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'five': 5, 'one': 1}
使用collections.defaultdict
,它是dict
的子类。 这会将任何键的默认值设置为空列表,并允许您轻松追加。 以下是您要寻找的猜测:
from collections import defaultdict
l_s = ['one', 1, 'two', 2, 'three', 3, 'four', 4, 'five', 5, 'six', 6]
d = defaultdict(list)
for txt, num in zip(l_s[::2], l_s[1::2]):
d[txt].append(num)
# defaultdict(list,
# {'five': [5],
# 'four': [4],
# 'one': [1],
# 'six': [6],
# 'three': [3],
# 'two': [2]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.