Python:从数组中分配变量

时间:2015-10-06 17:26:27

标签: python list iterable-unpacking

我在Python中有一些代码:

repost_pid = row[0]
repost_permalink = row[1]
repost_domain = row[2]
repost_title = row[3]
repost_submitter = row[4]

是否有一种单行方式来分配这些变量?

另外,如果我想跳过一个值,我会怎么做?

3 个答案:

答案 0 :(得分:5)

是的,您可以使用,分隔每个变量来执行unpacking

repost_pid, repost_permalink, repost_domain, repost_title, repost_submitter = row

如果有一个您不关心的特定值,the convention is to assign it to an underscore variable,例如

repost_pid, repost_permalink, _, repost_title, repost_submitter = row

答案 1 :(得分:1)

repost_pid,repost_permalink, repost_domain, repost_title, repost_submitter = row[0], row[1], row[2], row[3], row[4]

但它不可读

答案 2 :(得分:0)

如果要在序列解包中跳过值,可以执行以下操作:

>>> row
[0, 1, 2, 3]
>>> r0,r1,r3=row[0:2]+[row[3]]
>>> r0,r1,r3
(0, 1, 3)