【问题标题】:Can anyone help me to optimize this piece of code?谁能帮我优化这段代码?
【发布时间】:2019-08-28 17:18:27
【问题描述】:

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

我在 Jupyter notebook 中试过这个

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]

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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]

【讨论】:

  • 这毫无意义。为什么要使用列表推导,在同一推导内构建新列表时将其丢弃?
  • 不知道我在想什么。已编辑。
  • 预期输出表明列表中的数字应该是唯一的。
【解决方案2】:

使用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】:

有几种方法可以做到这一点。您可以使用集合库中的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})

【讨论】:

    【解决方案4】:

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

    通过使用简单的 for 循环,您只需触摸任何数字一次,它将保留原始顺序 - 将您的数字 through 放在一个集合可能无法做到 -不能保证一组中的顺序:

    保留一组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]
    

    【讨论】:

      【解决方案5】:

      您可以将list 函数应用于您的set 对象,以便 将其转换为列表。

      list_from_set = list(set(list_even))
      >>> print(list_from_set)
      [2, 4, 6, 8, 10, 12]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-03
        • 1970-01-01
        • 2020-10-29
        • 2020-08-13
        • 1970-01-01
        • 2020-01-08
        • 2022-12-06
        • 1970-01-01
        相关资源
        最近更新 更多