我想根据这样的要求存储元素列表:
a = ["I","have","something","to","buy"]
当循环到“ I”或“ have”或“ something”或“ buy”时,除当前循环的元素外,其他元素将存储在列表中。例如,我们循环到“某物”,因此将存储“ I”,“有”,“到”,“购买”。
我的代码:
store = []
for x in a:
if x:
#I stuck here, I am really sorry, I know I should give more example,
#but I really cant continue after here.
我的预期输出:
[["have","something","to","buy"], ["I","something","to","buy"], ["I","have","to","buy"], ["I","have","something","buy"], ["I","have","something","to"]]
答案 0 :(得分:1)
a = ["I","have","something","to","buy"]
store = []
for x in a:
s = []
for i in a:
if i == x:
continue
else:
s.append(i)
store.append(s)
print(store)
尝试一下
答案 1 :(得分:1)
您实际上是在从5个元素的列表中寻找4个元素的所有组合(无替换)。
使用itertools.combinations
:
from itertools import combinations
a = ["I", "have", "something", "to", "buy"]
print(list(combinations(a, 4)))
# [('I', 'have', 'something', 'to'), ('I', 'have', 'something', 'buy'),
# ('I', 'have', 'to', 'buy'), ('I', 'something', 'to', 'buy'),
# ('have', 'something', 'to', 'buy')]
答案 2 :(得分:1)
由于您只检查列表中已经存在的单词,因此可以将问题减少到:
wordLists = [a[:w]+a[w+1:] for w in range(len(a))]
输出:
[['have', 'something', 'to', 'buy'], ['I', 'something', 'to', 'buy'], ['I', 'have', 'to', 'buy'], ['I', 'have', 'something', 'buy'], ['I', 'have', 'something', 'to']]
答案 3 :(得分:1)
import itertools
a = ["I","have","something","to","buy"]
res = list(map(list, itertools.combinations(a, 4)))
print(res)
# [['I', 'have', 'something', 'to'], ['I', 'have', 'something', 'buy'], ['I', 'have', 'to', 'buy'], ['I', 'something', 'to', 'buy'], ['have', 'something', 'to', 'buy']]
请注意,itertools.combinations
默认情况下会生成tuples
。我已经使用map
转换为list
类型的对象。
答案 4 :(得分:1)
a = ["I","have","something","to","buy"]
[a[:idx]+a[idx+1:] for idx, v in enumerate(a)]
输出
[["have","something","to","buy"], ["I","something","to","buy"], ["I","have","to","buy"], ["I","have","something","buy"], ["I","have","something","to"]]
尝试这个简单的代码
答案 5 :(得分:0)
尝试
for i in a[:]:
tmp = a[:]
a.remove(i)
print(a)
a = tmp