3 回答

TA贡献2012条经验 获得超12个赞
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)
试试这个

TA贡献1843条经验 获得超7个赞
由于您只检查列表中已有的单词,因此您可以将问题简化为:
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']]

TA贡献1887条经验 获得超5个赞
您实际上是在从 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')]
添加回答
举报