Python 循环索引
Python loop indexing
我正在阅读一本关于 Python3 和线性代数的书。我正在尝试获取格式为 'name junk junk 1 1 1 1 1' 的字符串,并制作一个字典,其中的名称和数字从字符串转换为整数。即 {name:[1,1,1,1,1]} 但我不太明白循环,因为我是 python 新手。这是我的代码:
string = 'Name junk junk -1 -1 1 1'
for i, x in string.split(" "):
if i == 0:
a = x
if i > 2:
b = int(x)
运行 该代码出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
理想情况下,我也希望它是一种理解。但如果我能得到循环,我可能会弄清楚那部分。
您是要使用 enumerate
吗?
for i, x in enumerate(string.split(" ")):
# ...
使用列表理解:
tokens = string.split() # Splits by whitespace by default, can drop " "
result = {tokens[0]: [int(x) for x in tokens[3:]]} # {'Name': [-1, -1, 1, 1]}
我正在阅读一本关于 Python3 和线性代数的书。我正在尝试获取格式为 'name junk junk 1 1 1 1 1' 的字符串,并制作一个字典,其中的名称和数字从字符串转换为整数。即 {name:[1,1,1,1,1]} 但我不太明白循环,因为我是 python 新手。这是我的代码:
string = 'Name junk junk -1 -1 1 1'
for i, x in string.split(" "):
if i == 0:
a = x
if i > 2:
b = int(x)
运行 该代码出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
理想情况下,我也希望它是一种理解。但如果我能得到循环,我可能会弄清楚那部分。
您是要使用 enumerate
吗?
for i, x in enumerate(string.split(" ")):
# ...
使用列表理解:
tokens = string.split() # Splits by whitespace by default, can drop " "
result = {tokens[0]: [int(x) for x in tokens[3:]]} # {'Name': [-1, -1, 1, 1]}