谁能帮助我优化这段代码?

时间:2019-04-07 11:26:39

标签: python python-3.x

我想将偶数和奇数存储在单独的列表中。但是,这里我面临一个独特的问题。我可以将其存储在集合中,但不能存储在列表中。有没有一种方法可以将它们存储在列表中而无需重复。

我已经在Jupyter笔记本中尝试过

list_loop=[1,2,3,4,5,6,7,8,9,10,11,12,13,1,4,1,51,6,17,]
for i in list_loop:
    if i % 2 == 0 :
        list_even = list_even + [i]
    else:
        list_odd = list_odd + [i]
print(set(list_even))
print(set(list_odd))

预期输出:

[2,4,6,8,10,12]
[1,3,5,7,9,11,13,17,51]

5 个答案:

答案 0 :(得分:0)

您可以将const input = [ {_id: "5ca8b8ca0f1b2f54646ded9a", question: "Do you like it ?", answer: "yes"}, {_id: "5ca8b8ca0f1b2f54646ded99", question: "Do you like it ?", answer: "no"}, {_id: "5ca8b8f80f1b2f54646deda1", question: "Where are you ?", answer: "home"}, {_id: "5ca8b8f80f1b2f54646deda0", question: "Where are you ?", answer: "home"} ]; const groupByQuestionAndAnswers = Object.values(input.reduce((accu, {question, answer}) => { if(!accu[question]) accu[question] = {question}; if(!accu[question][answer]) accu[question][answer] = {answer, count: 0}; accu[question][answer].count += 1; return accu; }, {})); const output = groupByQuestionAndAnswers.map(({question, ...res}) => { return {question, answers: Object.values(res)}; }); console.log(output);函数应用于list对象,以便 将其转换为列表。

set

答案 1 :(得分:0)

有两种方法可以做到这一点。您可以在集合库中使用OrderedDict,也可以对集合进行排序并获得列表,

...
print(sorted(set(list_even)))
print(sorted(set(list_odd)))

此外,我将使用一组理解力来亲自创建这些列表

list_even = sorted({x for x in list_loop if x % 2 == 0})
list_odd = sorted({x for x in list_loop if x % 2 == 1})

答案 2 :(得分:0)

使用comprehension

>>> list_loop=[1,2,3,4,5,6,7,8,9,10,11,12,13,1,4,1,51,6,17,]
>>> print(list(set(_ for _ in list_loop if _ % 2)))
[1, 3, 5, 7, 9, 11, 13, 17, 51]

偶数。

答案 3 :(得分:0)

list_oddlist_even定义为列表,并且在打印之前不要将它们转换为集合。请注意,您可以使用列表推导来填充list_oddlist_even

list_odd = []
list_even = []

list_loop=[1,2,3,4,5,6,7,8,9,10,11,12,13,1,4,1,51,6,17,]
list_odd = [elem for elem in list_loop if elem % 2 != 0]
list_even = [elem for elem in list_loop if elem % 2 == 0]

print(list_even)
print(list_odd)

输出:

[2, 4, 6, 8, 10, 12, 4, 6]
[1, 3, 5, 7, 9, 11, 13, 1, 1, 51, 17]

编辑:为获得唯一性,将list_loop变成一组:

list_loop=set([1,2,3,4,5,6,7,8,9,10,11,12,13,1,4,1,51,6,17,])

输出:

[2, 4, 6, 8, 10, 12]
[1, 3, 5, 7, 9, 11, 13, 17, 51]

答案 4 :(得分:0)

您可以使用带有过滤条件的列表理解来解决此问题-但是然后您将列表重复两次。

通过使用简单的for循环,您只需触摸一次一次即可,它会保留原始顺序-将数字放在 组中可能不会做些什么-不能保证组合中的顺序:

保留一组seen数字,仅在未显示当前数字时添加任何内容。

list_loop = [1,2,3,4,5,6,7,8,9,10,11,12,13,1,4,1,51,6,17,]

list_even = []
list_odd = [] 
seen = set()

trick = [list_even, list_odd]  # even list is at index 0, odd list at index 1

for i in list_loop:
    if i in seen: 
        continue
    else:
        seen.add(i)
                                 # the trick eliminates the need for an if-clause
        trick[i%2].append(i)     # you use i%2 to get either the even or odd index


print(list_even)
print(list_odd)

输出:

[2, 4, 6, 8, 10, 12]
[1, 3, 5, 7, 9, 11, 13, 51, 17]