簡體   English   中英

在另一個列表中附加列表

[英]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使用引用來存儲列表中的元素。 當你使用append時,它只是將對s的引用存儲在A中。當你清除列表時,它也會在A中顯示為空白。 如果要在A中制作列表的獨立副本,可以使用復制方法。

當您在列表“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)

或者你可以在沒有“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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM