Skip to main content
 首页 » 编程设计

python之将非顺序列表元素分配给变量

2025年05月04日19softidea

我在 \t 上拆分文件的一行并将每个部分保存在名为 parts 的列表中:

with open(in_file, 'r') as file: 
    for l in file: 
        parts = l.rstrip().split('\t') 

然后我想将一些元素分配给变量。

在 Perl 中我会这样做:

my @parts = split(/\t/);     
my ($start, $end, $name, $length, $id) = @parts[0,2,3,4,11]; 

如何在 Python 中实现这一点?我想做一些等同于:

start, end, name, length, id = parts[0,2,3,4,11]  # Doesn't work 

相对于:

start = parts[0] 
end = parts[2] 
... 

我知道我可以像这样分配一系列元素:

start, other_var, end = parts[0:3] 

但是,如果我想要的元素是非连续的,我该怎么做呢?

请您参考如下方法:

您将使用 operator.itemgetter在返回所选项目的元组的 Python 中:

from operator import itemgetter 
 
start, end, name, length, id = itemgetter(0,2,3,4,11)(parts)  

当然还有其他方法,但这些可能不是明显的方法。


  1. 使用列表理解。这会构建一个列表,此处可能不需要:

    indices = 0,2,3,4,11 
    start, end, name, length, id = [parts[i] for i in indices] 
    

  1. 将 map 与 list.__getitem__ 结合使用。这也在 Python 2 中构建了一个列表,更重要的是,通过魔术方法做事有时会让人感到毛骨悚然:

    indices = 0,2,3,4,11 
    start, end, name, length, id = map(parts.__getitem__, indices) 
    

  1. 还有 numpy 有一个 basic/advanced indexing syntax , 但只有在之后对数组进行代数运算时才应使用它,而且还必须安装 numpy:

    import numpy as np 
     
    indices = 0,2,3,4,11 
    start, end, name, length, id = np.array(parts)[indices]