Python,匹配两个列表的元素
x= [0,2,3,5,6];
y= [64,384,1024,4096,384];
上面是我正在使用的两个数组。我试图以Pythonic方式将元素匹配在一起,
例如:
如果xType
是2,我想计算一个名为yType
的变量来对应于它在y中的值(位置明智) 。所以我应该得到y = 384
。如果 xType = 3 我应该得到 1024。
我该如何做呢
x= [0,2,3,5,6];
y= [64,384,1024,4096,384];
The above are two arrays I'm using. Im trying to match the elements together in a pythonic way
example:
if xType
is 2 i want to compute a variable called yType
to correspond to its value(position wise) in y. so i should get y = 384
. if xType = 3
i should get 1024.
How would i go about doing this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的具体目标是从给定的两个列表中生成一个
dict
,请使用zip
:并去掉那些分号!
如果您不需要映射类型,而只想创建项目对,则单独使用
zip
即可:If your specific aim is to generate a
dict
from the two lists you've given, usezip
:And get rid of those semicolons!
If you don't need a mapping type, but just want to create pairs of items,
zip
alone will do:这太短了,甚至 Stack Overflow 也不允许我提交如此简短的答案:
这将从 y 中返回与 2 或任何其他给定值的位置相对应的元素从
x
列表中。希望它有帮助
:)事实上,字典可能是您需要的东西。尝试使用它们。
This is so short, even Stack Overflow did not allow me to submit such a short answer:
This will return element from
y
corresponding to the position of2
or any other given value from withinx
list.Hope it helped :)
Ps. Indeed dictionaries may be something you need. Try using them.
如果
x
中的元素是唯一的,您可以将它们用作 dict 查找 y 中具有相同索引的元素。像这样:如果您想要进行大量查找,但如果您只想进行一次查找,这很有用 Tadeck 的回答效率更高
If the elements in
x
are unique, you can use them as the keys in a dict to lookup the elements iny
that have the same index. Like this:This is useful if you want to do lots of lookups, but if you want to do just one lookup Tadeck's answer is more efficient
查找“python 中的地图”或类似的内容
look up 'maps in python' or something like that
但是,如果您还需要在 x 中查找 y 中的元素,则还需要
yxmap
。如果您出于某种原因需要将它们作为列表(可能是因为您在程序过程中修改它们),您可以使用i = x.index(2)
,然后使用y[i]
。However, if you also need to lookup elements in x for y, you'll need a
yxmap
as well. And if you need these to be lists for some reason (perhaps because you're modifying them during the course of your program), you could usei = x.index(2)
and theny[i]
.