[英]Last added element value reflected in whole list in python - How to solve this problem?
以下是我的数据:
"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2
我想把它放到一个列表中,使它看起来像这样:
["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2]
我的问题是只有最后一个元素被推送到整个列表中。 结果如下所示:
["Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2,"Raj": 2,"Jay": 2]
我将如何解决这个问题?
tou 使用dict
它有一个unique key value par properties
,为什么当你和 new 它将更新最后添加键值 par 如果没有任何键它将添加新键
如果您确实要替换最后一个元素,它将适用于
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]
或者您可以通过map 过滤器减少方法进行操作
使用这些东西,如果有任何问题让我知道,如果它有效,请告诉我
不要使用dict
,而是使用list
和tuple
:
your_list = [ ('Jay', 1), ('Raj', 3), ('Jay', 1), ('Raj', 3) ]
使用dict
时,您不能使用相同的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.