繁体   English   中英

如何打印 python 列表中的特定项目?

[英]How do I print specific items from a python list?

我正在尝试从 Python 的列表中打印多个项目。 我看过很多例子,但我无法让它们工作。 什么是根据列表索引从导入列表中打印项目的好方法。

我的代码中注释掉的示例是我认为可行的,但找不到简单的解决方案。

items = []

with open('input.txt') as input_file:
    for line in input_file:
        items.append(line)

print(items[5],items[6])
#print(items[5,6,7]

一种方法是使用 for 循环。

item_list = ['a','b','c','d','e','f','g','i']  # an example list.
index_to_print = [5,6,7]  # add all index you want to print to this list.

for i in item_list:
    if item_list.index(i) in index_to_print:
        print(i)

更新:我们可以循环遍历要打印的索引,而不是遍历整个 item_list。

for i in index_to_print:
    if i < len(item_list):
        print(item_list[i])
    else:
        print('given index is out of range.')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM