简体   繁体   English

最后添加的元素值反映在 python 的整个列表中 - 如何解决这个问题?

[英]Last added element value reflected in whole list in python - How to solve this problem?

The following is my data:以下是我的数据:

"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2

I would like to put it into a list to make it look like this:我想把它放到一个列表中,使它看起来像这样:

["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]

My issue is that only the final element is pushed to the entire list.我的问题是只有最后一个元素被推送到整个列表中。 The result looks like this:结果如下所示:

["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]

How would I resolve this issue?我将如何解决这个问题?

tou use dict it has a unique key value par properties that why when you and new it will update last add key value par if not has any key it will add new key tou 使用dict它有一个unique key value par properties ,为什么当你和 new 它将更新最后添加键值 par 如果没有任何键它将添加新键

It will work on list of list if you do want replace last element then try following way may be your problem solve如果您确实要替换最后一个元素,它将适用于list of list然后尝试以下方式可能是您的问题解决

list_var = []
list_var.append(['Jay',1])
print(list_var) #[['Jay',1]]

#you can append list using append method so list is ordered collection so add another one

list_var.append(['Raj',1])
print(list_var) #[['Jay',1],['Raj',1]]

#add another
list_var.append(['Jay',3])
print(list_var) #[['Jay',1],['Raj',1],['Jay',3]]

#using for you will print
for name,score in list_var:
    print(name,score)

#or you will access by index
list_var[0] #[['Jay',1]

Or you can manipulate by map filter reduce method或者您可以通过map 过滤器减少方法进行操作

Using this stuff may you understand if any problem let me know and if it's work then let me know使用这些东西,如果有任何问题让我知道,如果它有效,请告诉我

Don't use dict , use list and tuple instead:不要使用dict ,而是使用listtuple

your_list = [ ('Jay', 1), ('Raj', 3), ('Jay', 1), ('Raj', 3) ]

When using dict you cannot use same keys.使用dict时,您不能使用相同的键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM