Python循环索引

Joe*_*ith 0 python indexing loops

我正在写一本关于Python3和线性代数的书.我正在尝试使用格式'name junk junk 1 1 1 1 1'的字符串,并创建一个字典,其中包含名称和从字符串转换为整数的数字.即{name:[1,1,1,1,1]}但我无法弄清楚循环,因为我是一个蟒蛇新手.这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

运行该代码会发出以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
Run Code Online (Sandbox Code Playgroud)

理想情况下,我也希望它是一种理解.但是,如果我能得到循环,我可能会想出那个部分.

vau*_*tah 5

你的意思是用enumerate吗?

for i, x in enumerate(string.split(" ")):
     # ...
Run Code Online (Sandbox Code Playgroud)

使用列表理解:

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]}
Run Code Online (Sandbox Code Playgroud)