각 하위 목록의 첫 번째 항목 추출
목록 목록에서 각 하위 목록의 첫 번째 항목을 추출하여 새 목록에 추가하는 가장 좋은 방법이 무엇인지 궁금합니다. 그래서 내가 가지고 있다면 :
lst = [[a,b,c], [1,2,3], [x,y,z]]
내가 꺼내 싶은 a
, 1
그리고 x
그와는 별도의 목록을 만들 수 있습니다.
나는 시도했다 :
lst2.append(x[0] for x in lst)
목록 이해 사용 :
>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']
당신은 우편 번호를 사용할 수 있습니다 :
>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)
또는 zip
목록을 생성하지 않는 Python 3 :
>>> list(zip(*lst))[0]
(1, 11, 21)
또는,
>>> next(zip(*lst))
(1, 11, 21)
또는 (내가 가장 좋아하는) numpy를 사용하십시오.
>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1, 2, 3],
[11, 12, 13],
[21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])
Python에는 itemgetter라는 함수가 포함되어있어 목록의 특정 색인에있는 항목을 반환합니다.
from operator import itemgetter
검색하려는 항목의 색인을 itemgetter () 함수에 전달하십시오. 첫 번째 항목을 검색하려면 itemgetter (0)을 사용합니다. 이해해야 할 중요한 것은 itemgetter (0) 자체가 함수를 반환한다는 것입니다. 해당 함수에 목록을 전달하면 특정 항목이 나타납니다.
itemgetter(0)([10, 20, 30]) # Returns 10
이것은 함수를 첫 번째 인수로 사용하는 map ()과 두 번째 인수로 목록 (또는 다른 반복 가능)을 사용하는 map ()과 결합 할 때 유용합니다. iterable에서 각 객체에 대해 함수를 호출 한 결과를 반환합니다.
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
map ()은 제너레이터를 반환하므로 결과는 실제 목록을 얻기 위해 list ()로 전달됩니다. 요약하면 다음과 같이 작업을 수행 할 수 있습니다.
lst2.append(list(map(itemgetter(0), lst)))
이것은 목록 이해를 사용하기위한 대체 방법이며 컨텍스트, 가독성 및 선호도에 따라 크게 선택할 수 있습니다.
추가 정보 : https://docs.python.org/3/library/operator.html#operator.itemgetter
같은 문제가 있었고 각 솔루션의 성능에 대해 궁금했습니다.
여기 있습니다 %timeit
:
import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
배열을 변환하는 첫 번째 numpy-way :
%timeit list(np.array(lst).T[0])
4.9 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
목록 이해 (@alecxe에서 설명)를 사용하는 완전히 기본 :
%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Another native way using zip
(as explained by @dawg):
%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Second numpy-way. Also explained by @dawg:
%timeit list(np.array(lst)[:,0])
4.95 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final list
saves about one µs which is still in the 10x difference.
Note that, when I surrounded each code snippet with a call to len
, to ensure that Generators run till the end, the timing stayed the same.
Your code is almost correct. The only issue is the usage of list comprehension.
If you use like: (x[0] for x in lst), it returns a generator object. If you use like: [x[0] for x in lst], it return a list.
When you append the list comprehension output to a list, the output of list comprehension is the single element of the list.
lst = [["a","b","c"], [1,2,3], ["x","y","z"]]
lst2 = []
lst2.append([x[0] for x in lst])
print lst2[0]
lst2 = [['a', 1, 'x']]
lst2[0] = ['a', 1, 'x']
Please let me know if I am incorrect.
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
outputlist.append(values[0])
print(outputlist)
Output: ['a', 1, 'x']
You said that you have an existing list. So I'll go with that.
>>> lst1 = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [1, 2, 3]
Right now you are appending the generator object to your second list.
>>> lst2.append(item[0] for item in lst)
>>> lst2
[1, 2, 3, <generator object <genexpr> at 0xb74b3554>]
But you probably want it to be a list of first items
>>> lst2.append([item[0] for item in lst])
>>> lst2
[1, 2, 3, ['a', 1, 'x']]
Now we appended the list of first items to the existing list. If you'd like to add the items themeselves, not a list of them, to the existing ones, you'd use list.extend. In that case we don't have to worry about adding a generator, because extend will use that generator to add each item it gets from there, to extend the current list.
>>> lst2.extend(item[0] for item in lst)
>>> lst2
[1, 2, 3, 'a', 1, 'x']
or
>>> lst2 + [x[0] for x in lst]
[1, 2, 3, 'a', 1, 'x']
>>> lst2
[1, 2, 3]
https://docs.python.org/3.4/tutorial/datastructures.html#more-on-lists https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions
참고URL : https://stackoverflow.com/questions/25050311/extract-first-item-of-each-sublist
'IT story' 카테고리의 다른 글
PHP에서 디렉토리와 그 전체 내용 (파일 + 하위 디렉토리)을 재귀 적으로 삭제하려면 어떻게합니까? (0) | 2020.07.11 |
---|---|
카운트를 통해 그룹과 Linq (0) | 2020.07.10 |
HTML 페이지를 인쇄하는 동안 여백 (0) | 2020.07.10 |
하스켈 함수 구성 (.) 및 함수 적용 ($) 관용구 : 올바른 사용법 (0) | 2020.07.10 |
Rspec, Rails : 컨트롤러의 프라이빗 메소드를 테스트하는 방법? (0) | 2020.07.10 |