python - 如何只访问列表的特定元素

标签 python python-3.x

假设我有一个这样的列表:

myList = ["Sprite", "Fanta", "Coke", "7up"]

我只想访问 myList[0]myList[3],它们是 Sprite 和 7up。我试着用列表切片来做,但没做对。

最佳答案

如果您的需求是从知道索引的列表中访问多个元素,那么您可以使用operator.itemgetter

from operator import itemgetter
myList = ["Sprite", "Fanta", "Coke", "7up"]
index = [0,3]     # you can add as many indexes(valid ones) you want
print itemgetter(*index)(myList)  

输出

('Sprite', '7up')

关于python - 如何只访问列表的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51245098/

相关文章:

python - 猜词器无法打印足够的字符

使用 types.FunctionType 时的 Python 版本问题

python - 如何接受python json字典中的任何键?

python - 为多索引数据框的每个级别查找最小值

python - 遍历 df 的所有值以替换零值

python - 使用 Python 和 Linux 获取远程 MAC 地址

python - Pandas DataFrame 迭代切片

python - 在 pandas groupby 之后合并成对的行,如果 ID 在 df 中没有出现两次,则给出 NaN 值

python - 如何使用 py.test 收集我的测试?

python - 无模块名称加密