python - 基于字典值映射Python列表

我想根据字典的值映射 python 列表。当我有 pandas 系列时,我知道该怎么做,但我不知道如何使用列表:

l = ['apple', 'lemmon', 'banana']
x = {'apple':1, 'lemmon':2, 'banana':3, 'chery':4}

l = l.map(x)
print(l)

期望的输出:

l = [1,2,3]

最佳答案

这可以通过 Python 列表理解来解决。 在你的情况下:

l = [x[key] for key in l]

请注意,l 中的所有元素都需要作为 x 中的键存在。

https://stackoverflow.com/questions/67476143/

相关文章:

visual-studio-code - 删除 VSCode 中的 Sublime 文本主题

react-native - 部署 key 为空 appcenter 代码推送 cli

python - 将 VSCode 更新到 1.56.1 后,出现错误 : "Cannot acti

c++ - 在 C++ 中定义类枚举值的 std::vector 的缩写语法

python - 如何获取字典中最大值的键,如果有重复,还返回最大数字键

python - Python 中的 Hangman 游戏

django - 从在 WSL 上运行的 django 连接到在 Windows 上运行的 Post

reactjs - 在@auth0 中 Jest 模拟 Auth0Client

apache-spark - Spark 窗口函数中的条件

emacs - 如何更改 emacs 中行号模式的背景颜色?