簡體   English   中英

python從列表中選擇特定元素

[英]python select specific elements from a list

是否有一種“pythonic”方式可以只從列表中獲取某些值,類似於這個 perl 代碼:

my ($one,$four,$ten) = line.split(/,/)[1,4,10]

使用列表理解

line = '0,1,2,3,4,5,6,7,8,9,10'
lst = line.split(',')
one, four, ten = [lst[i] for i in [1,4,10]]

我認為您正在尋找operator.itemgetter

import operator
line=','.join(map(str,range(11)))
print(line)
# 0,1,2,3,4,5,6,7,8,9,10
alist=line.split(',')
print(alist)
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
one,four,ten=operator.itemgetter(1,4,10)(alist)
print(one,four,ten)
# ('1', '4', '10')
lst = line.split(',')
one, four, ten = lst[1], lst[4], lst[10]

嘗試operator.itemgetter (在 python 2.4 或更新版本中可用):

返回一個可調用對象,該對象使用操作數的 ____getitem____() 方法從其操作數中獲取項目。 如果指定了多個項目,則返回查找值的元組。

>>> from operator import itemgetter
>>> line = ','.join(map(str, range(11)))
>>> line
'0,1,2,3,4,5,6,7,8,9,10'
>>> a, b, c = itemgetter(1, 4, 10)(line.split(','))
>>> a, b, c
('1', '4', '10')

濃縮:

>>> # my ($one,$four,$ten) = line.split(/,/)[1,4,10]
>>> from operator import itemgetter
>>> (one, four, ten) = itemgetter(1, 4, 10)(line.split(','))

這個怎么樣:

index = [1, 0, 0, 1, 0]
x = [1, 2, 3, 4, 5]
[i for j, i in enumerate(x) if index[j] == 1]
#[1, 4]

是的:

data = line.split(',')
one, four, ten = data[1], data[4], data[10]

你也可以使用itemgetter,但我更喜歡上面的代碼,它更清晰,清晰==好代碼。

或者,如果您有一個 Numpy 數組而不是列表,您可以執行以下操作:

from numpy import array

# Assuming line = "0,1,2,3,4,5,6,7,8,9,10"
line_array = array(line.split(","))

one, four, ten = line_array[[1,4,10]]

這里的技巧是您可以將列表(或 Numpy 數組)作為數組索引傳遞。

編輯:我首先認為它也適用於元組,但它有點復雜。 我建議堅持使用列表或數組。

使用熊貓:

import pandas as pd
line = "0,1,2,3,4,5,6,7,8,9,10"
line_series = pd.Series(line.split(','))
one, four, ten = line_series[[1,4,10]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM