Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过将列表与另一个列表进行比较来更改列表中的顺序_Python_List - Fatal编程技术网

Python 通过将列表与另一个列表进行比较来更改列表中的顺序

Python 通过将列表与另一个列表进行比较来更改列表中的顺序,python,list,Python,List,我无法控制元素在列表中的位置。我有以下代码: name= ['a', 'b', 'c','d','e'] year= [10,20,30,40,50] ID= ['a', 'c', 'd'] df = pd.DataFrame({'Name' : name, 'age' : year}) x= list(set(name).intersection(ID)) print (x) y=df[df['Name'].isin(x)]['age'] print(y) 我得到的结果是: ['c', 'a

我无法控制元素在列表中的位置。我有以下代码:

name= ['a', 'b', 'c','d','e']
year= [10,20,30,40,50]
ID= ['a', 'c', 'd']
df = pd.DataFrame({'Name' : name, 'age' : year})
x= list(set(name).intersection(ID))
print (x)
y=df[df['Name'].isin(x)]['age']
print(y)
我得到的结果是:

['c', 'a', 'd']
0    10
2    30
3    40

这就是我困惑的地方。列表
name
year
应该是相关的,所以
a和10,b和20….
但是当我打印
x
y
时,我得到
c和10,a和30,b和40
。我认为python会自动将
y
从升序排序到降序排序。我如何修正
y
以获得
30,10,40
而不是
10,30,40

,因为在将
list
转换为
set
后,您打破了原始列表的顺序,所以要修正它:

反而

x= list(set(name).intersection(ID))
您应该过滤原始列表,例如通过列表理解:

x= [i for i in name if i in ID]

您感到困惑,因为在将
list
转换为
set
后,您打破了原始列表的顺序,因此要修复它:

反而

x= list(set(name).intersection(ID))
您应该过滤原始列表,例如通过列表理解:

x= [i for i in name if i in ID]

为了得到您想要的,您可以使用来自df的相同子集,如下所示

name= ['a', 'b', 'c','d','e']
year= [10,20,30,40,50]
ID= ['a', 'c', 'd']
df = pd.DataFrame({'Name' : name, 'age' : year})
x= list(set(name).intersection(set(ID)))
print (x)
y=df[df['Name'].isin(x)].age.to_list()
y1= df[df['Name'].isin(x)].Name.to_list()
print(y)
print(y1)
结果

[10, 30, 40]
['a', 'c', 'd']

y
y1
将打印出您的期望值,它们在哪里匹配

以获得您想要的内容您可以使用来自df的相同子集,如下所示

name= ['a', 'b', 'c','d','e']
year= [10,20,30,40,50]
ID= ['a', 'c', 'd']
df = pd.DataFrame({'Name' : name, 'age' : year})
x= list(set(name).intersection(set(ID)))
print (x)
y=df[df['Name'].isin(x)].age.to_list()
y1= df[df['Name'].isin(x)].Name.to_list()
print(y)
print(y1)
结果

[10, 30, 40]
['a', 'c', 'd']

y
y1
将打印出您期望的结果,它们在哪里匹配

不按降序排序。只是集合不用于按顺序存储元素,顺序变得混乱。它不按降序排序。只是集合不用于按顺序存储元素,而且顺序会变得混乱。你应该用IDS做一个集合,这会有所帮助。谢谢你,你应该做一个有帮助的计划。非常感谢。