猿问

基于特定元素打印列表中的元素

我想根据这样的要求存储元素列表:


循环列表并检查每个字符串

如果是这个字符串,则将除当前字符串之外的其他字符串存储在列表中。

a = ["I","have","something","to","buy"]

当循环到“I”或“have”或“something”或“buy”时,除当前循环的元素外,其他元素将存储在列表中。例如,我们循环到“something”,因此将存储“I”、“have”、“to”、“buy”。


我的代码:


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"]]


喵喵时光机
浏览 189回答 3
3回答

繁花如伊

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)试试这个

蓝山帝景

由于您只检查列表中已有的单词,因此您可以将问题简化为: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']]

慕工程0101907

您实际上是在从 5 个元素的列表中寻找 4 个元素(没有替换)的所有组合。使用itertools.combinations:from itertools import combinationsa = ["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')]
随时随地看视频慕课网APP

相关分类

Python
我要回答