根据特定元素在列表中打印元素

时间:2018-10-10 07:05:03

标签: python list

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

  1. 环绕列表并检查每个字符串
  2. 如果是此字符串,则将列表中除当前字符串外的其他字符串存储。
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"]]

6 个答案:

答案 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)

改为使用itertools.combinations

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