在另一个列表中附加一个列表

Appending a list in another list

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

代码 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:

[[],[]]

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

A = []

for i in range(0,int(input())):
    name = input()
    score = float(input())

    A.append([name,score])

print(A)

这是预期的列表行为。 Python 使用引用来存储列表中的元素。当您使用追加时,它只是将对 s 的引用存储在 A 中。当您清除列表 s 时,它也会在 A 中显示为空白。如果想对A中的list做一个独立的拷贝,可以使用copy方法。

当您将列表 "A" 附加到列表 "s" 时,它会在 "A" 中创建 "s" 的引用,这就是为什么每当您调用 .clear "s" 上的方法它也清除 "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)

或者您可以不使用 "s",如 BenT 所回答。

您可以使用 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']]