简体   繁体   中英

unpacking a list in python

Somewhere I saw a piece of code where you can unpack a list in a for loop. Let's say that I have a list:

row = ['001', '15\n', '963789', '40\n', '741239', '80\n', '985697', '80\n', '854698', '35\n', '965874', '10\n']

what would be the for loop to unpack the list. I saw something similar to:

for emp_id,pay_rate,job1,hours_worked1,job2,hours_worked2,job3,hours_worked3,job4,hours_worked4,job5,hours_worked5 in row:

what's the correct syntax to unpack this list?

That only really works if you have a nested structure. For example:

l = [(1,2,3), (4,5,6), (7,8,9)]

for a,b,c in l:
    print a,b,c

[OUTPUT]
1 2 3
4 5 6
7 8 9

If you have a flat list like this:

l2 = [1,2,3,4,5]

You can do:

one, two, three, four, five = l2

简单分配:

emp_id,pay_rate,job1 = ['001', '15\n', '963789']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM