简体   繁体   中英

Printing specific values from list in Python 3

I was wondering if there is a different and shorter way to print specific values in a list without having to repeat print(num[x],num[x],num[x]) many times

num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]

print(num[5])
print(num[5], num[12])

Just loop like this:

for i in [5, 12]:
   print(num[i], end=' ')

You could use operator.itemgetter :

>>> from operator import itemgetter
>>> num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]
>>> itemgetter(5, 12)(num)
('5', 'c')

You could use list comprehension:

>>> num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]
>>> print( [num[x] for x in (5, 12)] )
['5', 'c']

You can simply define a function.

def getVal(List, *index):
    for x in index:
        print(List[x], end=" ")

 num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]
 getVal(num, 1, 5, 3)

 # 1 5 3

You can just map() what you want:

>>> num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]
>>> list(map(lambda x: num[x], [5, 12]))
['5', 'c']

You need a function :

num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]

def index_no(first,second):
    try:
        return (num[first],num[second])
    except IndexError:
        pass

print(index_no(5,12))

output:

('5', 'c')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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