【问题标题】:how do i create a new list M from an existing list L in python?如何从 python 中的现有列表 L 创建一个新列表 M?
【发布时间】:2022-08-18 17:32:51
【问题描述】:

该代码在列表 L 中获取用户输入,并仅按升序显示可被 5 或 7 整除的数字。

我需要列表 M 形式的输出,但我不知道如何执行它。 例如,

输入 4 5 35 7 8 9 14 10

输出 [5、7、10、14、35]

但我得到的输出是: - 5 7 10 14 35

我如何合并列表 M?

L=[int(i)for i in input().split()]

L.sort()

for i in L:

  if(i%5==0 and i%7==0):
    print(i)
  elif(i%5==0):
      print(i)
  elif(i%7==0):
        print(i)

    标签: python-3.x list user-input


    【解决方案1】:

    如果我理解正确,您可以在输出列表中添加结果并使用str.join 对其进行格式化:

    L = [int(i) for i in input().split()]
    L.sort()
    
    output = []
    for i in L:
        if i % 5 == 0 and i % 7 == 0:
            output.append(f"{i} is divisible by 5 and 7")
        elif i % 5 == 0:
            output.append(f"{i} is divisible by 5")
        elif i % 7 == 0:
            output.append(f"{i} is divisible by 7")
        else:
            output.append(f"{i} is not divisible by 5 or 7")
    
    print(", ".join(output))
    

    打印(例如):

    5 6 7 35
    5 is divisible by 5, 6 is not divisible by 5 or 7, 7 is divisible by 7, 35 is divisible by 5 and 7
    

    【讨论】:

    • 我很困惑,@andrej 它期望 str 实例和 int 被发现。我需要把它转换成str吗?
    • @Gray 是的,如果你使用 str.join 首先将所有数字转换为字符串(使用 str()
    • 谢谢@andrej,您的代码提供了帮助。但我意识到,我的问题是错误的。对不起,我只是一个初学者。
    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多