如何使用Python 3.5.1从列表中打印多个非连续值 [英] How to print multiple non-consecutive values from a list with Python 3.5.1

查看:205
本文介绍了如何使用Python 3.5.1从列表中打印多个非连续值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个列表,并希望从列表中选择一些要打印的项目.下面,我只想在索引0处打印熊",在索引3处打印袋鼠".我的语法不正确:

I have created a list and want to choose a handful of items to print from the list. Below, I'd just like to print out "bear" at index 0 and "kangaroo" at index 3. My syntax is not correct:

>>> animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
>>> print (animals[0,3])

回溯(最近一次通话最近):文件",第1行,在 打印(animals [0,3])TypeError:列表索引必须为整数 或切片,而不是元组

Traceback (most recent call last): File "", line 1, in print (animals[0,3]) TypeError: list indices must be integers or slices, not tuple

我尝试在索引之间留一个空格,但它仍然给出错误:

I tried with a space between the indexes but it still gives an error:

>>> print (animals[0, 3])

回溯(最近一次通话最近):文件",第1行,在 打印(animals [0,3])TypeError:列表索引必须为 整数或分片,而不是元组

Traceback (most recent call last): File "", line 1, in print (animals[0, 3]) TypeError: list indices must be integers or slices, not tuple

例如,我可以打印单个值或0到3的范围:

I am able to print a single value or a range from 0-3, for example, with:

>>> print (animals [1:4])
['python', 'peacock', 'kangaroo']

如何打印多个非连续的列表元素?

How can I print multiple non-consecutive list elements?

推荐答案

要从列表中选择任意项目,可以使用

To pick arbitrary items from a list you can use operator.itemgetter:

>>> from operator import itemgetter    
>>> print(*itemgetter(0, 3)(animals))
bear kangaroo
>>> print(*itemgetter(0, 5, 3)(animals))
bear platypus kangaroo

这篇关于如何使用Python 3.5.1从列表中打印多个非连续值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆