Joe Smith
Joe Smith

Reputation: 191

Python loop indexing

I'm working through a book on Python3 and linear algebra. I'm trying to take a string with the format 'name junk junk 1 1 1 1 1' and make a dictionary with the name in the and the numbers converted from strings to ints. i.e. {name:[1,1,1,1,1]} But I can't quite figure out the loop, as I'm a python newbie. Here's my code:

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)

Running that code nets the following error:

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

Ideally I'd also like it to be a comprehension. But I can probably figure that part out if I can get the loop.

Upvotes: 0

Views: 78

Answers (1)

vaultah
vaultah

Reputation: 46593

Did you mean to use enumerate?

for i, x in enumerate(string.split(" ")):
     # ...

Using a list comprehension:

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

Upvotes: 5

Related Questions