简体   繁体   中英

Python: for every element in list get a new list without that element

I have a list from which I want to generate all possible sublists with one element missing.

>>> a = [1, 2, 3, 4]
>>> something(a)
[[2,3,4], [1,3,4], [1,2,4], [1,2,3]]

Use itertools.combinations .

from itertools import combinations

a = [1, 2, 3, 4]
result = combinations(a, 3)

print(list(result))
# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

As per the documentation , combinations "are emitted in lexicographic ordering according to the order of the input iterable". Which for your purposes means that the last element will be missing from the first item in the result, then the second last will be missing from the second item and so on. If you need the first element to be missing from the first item in the result and so on, you will have to reverse it usingreversed() , like this: reversed(list(combinations(a, 3))) .

Also, keep in mind that combinations returns a generator, so if you want it in list form or if you want to view it you have to convert it into a list first.

For each list index i , take the elements before i and the elements after i :

for i in range(len(a)):
    yield a[:i] + a[i+1:]

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