【问题标题】:Find squares of even and odd numbers in the given list在给定列表中查找偶数和奇数的平方
【发布时间】:2017-02-08 09:59:43
【问题描述】:

我有一个列表L = [1, 2, 3, 4, 5, 6, 7, 8],我想找到L 中所有偶数的平方和L 中所有奇数的平方。

例如,L = [2, 4, 6, 8] 应为[4, 16, 36, 64]L = [1, 3, 5, 7, 9] 应为[1, 9, 25, 49, 81]

我已经这样尝试过,但结果我无法获取列表:

num=input("enter the number:")
# num=[1,2,3,4,5,6,7,8,9]
if (num%2==0):
    print "The number is even"
    print num*num
else:
    print "The number is odd"
    print num*num

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    这需要列表理解,但你不能,因为有 2 个目标列表(你可以,但这意味着要测试两次均匀性)。

    因此定义 2 个输出列表,并使用三元表达式在输入列表中循环选择一个或另一个列表,这样您就可以执行唯一的 append(更优雅)

    L1=[1,2,3,4,5,6,7,8]
    
    even_sq,odd_sq = [],[]
    
    for i in L1:
        (even_sq if i%2==0 else odd_sq).append(i*i)
    
    print(even_sq,odd_sq)
    

    结果:

    [4, 16, 36, 64] [1, 9, 25, 49]
    

    【讨论】:

      【解决方案2】:

      使用 for 循环遍历列表,检查每个数字是偶数还是奇数,然后将每个 num 的平方附加到正确的列表中:

      odd_squares = []
      even_squares = []
      for num in L1:
          if (num % 2) == 0:
              even_squares.append(num ** 2)
          else:
              odd_squares.append(num ** 2)
      

      【讨论】:

        【解决方案3】:

        您可以使用列表推导来实现您想要的:

        L = [1, 2, 3, 4, 5, 6, 7, 8]
        even_squares = [e * e for e in L if e % 2 == 0]
        odd_squares = [e * e for e in L if e % 2 != 0]
        print(odd_squares, even_squares)
        

        输出:

        [1, 9, 25, 49] [4, 16, 36, 64]
        

        【讨论】:

          【解决方案4】:

          这类似于 Jean-François 的解决方案,但通过直接索引适当的列表来避免三元表达式:

          L = [1, 2, 3, 4, 5, 6, 7, 8]
          
          def even_odd_squares(l):
              r = [[], []]
          
              for ll in l:
                  r[ll%2].append(ll*ll)
          
              return r
          
          even, odd = even_odd_squares(L)
          print(even, odd) # [4, 16, 36, 64] [1, 9, 25, 49]
          

          【讨论】:

            【解决方案5】:

            这样好吗?

            def get_even_odd_squares(no_range):
                even_squares, odd_squares = [], []
                for no in no_range:
                    if no % 2 == 0:
                        even_squares.append(no ** 2)
                    else:
                        odd_squares.append(no ** 2)
                return even_squares, odd_squares  # ([4, 16, 36, 64], [1, 9, 25, 49, 81])
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-10-28
              • 2021-12-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-04-21
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多