【问题标题】:Appending a list in another list在另一个列表中附加一个列表
【发布时间】:2019-07-13 03:59:13
【问题描述】:

我不知道这两个东西是如何工作的,以及它们的输出。如果有更好的方法来做同样的工作。

代码 1:

A = []
s = []
for i in range(0,int(input())):
    name = input()
    score = float(input())
    s.append(name)
    s.append(score)
    A.append(s)
    s = []
print(A)

输出1:

[['firstInput', 23.33],['secondInput',23.33]]

代码2:

A = []
s = []
for i in range(0,int(input())):
    name = input()
    score = float(input()) 
    s.append(name)
    s.append(score)
    A.append(s)
    s.clear()
print(A)

输出 2:

[[],[]]

【问题讨论】:

    标签: python python-3.x list nested-lists


    【解决方案1】:

    有更好的方法可以做到这一点,但您根本不需要 list s

    A = []
    
    for i in range(0,int(input())):
        name = input()
        score = float(input())
    
        A.append([name,score])
    
    print(A)
    

    【讨论】:

    • 第一个和第二个输出呢?
    • 输出将取决于input。你能澄清你的问题吗?
    【解决方案2】:

    这是预期的列表行为。 Python 使用引用将元素存储在列表中。当您使用 append 时,它只是将 s 的引用存储在 A 中。当您清除列表 s 时,它也会在 A 中显示为空白。如果要对A中的列表s进行独立的复制,可以使用copy方法。

    【讨论】:

    • 看到第一个代码,心里有个疑问。为什么代码中的第 9 行对输出没有任何明显的影响?
    • 您在使用s = [] 时创建了一个同名的新列表。当您使用 clear 时,您更改了存储在 A 中的列表的值。也不推荐第一种方法,因为它会导致不需要的行为
    【解决方案3】:

    当您将列表“A”与列表“s”附加时,它会在“A”中创建“s”的引用,这就是为什么每当您在“s”上调用.clear 方法时,它会清除其中的元素“A”也是如此。

    在代码 1 中,您正在初始化一个具有相同名称“s”的新列表,一切正常。

    在代码 2 中,您在“s”上调用 .clear 方法,这会产生问题。

    为了使用代码 2 并获得预期的结果,您可以这样做:

    A = []
    s = []
    for i in range(0,int(input())):
        name = input()
        score = float(input()) 
        s.append(name)
        s.append(score)
        A.append(s[:])    # It copies the items of list "s"
        s.clear()
    print(A)
    

    或者你可以不用 BenT 回答的“s”。

    【讨论】:

      【解决方案4】:

      您可以使用list comprehension 来获取您的结果:-

      A = [ [ x for x in input("Enter name And score with space:\t").split() ] 
          for i in range(0, int(input("Enter end range:\t")))]
      print(A)
      

      输出

      Enter end range:    2
      Enter name And score with space:    rahul 74
      Enter name And score with space:    nikhil 65
      [['rahul', '74'], ['nikhil', '65']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2021-03-17
        • 1970-01-01
        • 2022-10-25
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        相关资源
        最近更新 更多