我想知道是否有一种不同的更短的方式来打印列表中的特定值,而不必多次重复打印(num [x],num [x],num [x])
num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"]
print(num[5])
print(num[5], num[12])
答案 0 :(得分:6)
像这样循环:
for i in [5, 12]:
print(num[i], end=' ')
答案 1 :(得分:2)
您可以使用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')
答案 2 :(得分:1)
您可以使用列表理解:
>>> 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']
答案 3 :(得分:1)
您可以简单地定义一个功能。
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
答案 4 :(得分:1)
您只需map()
即可:
>>> 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']
答案 5 :(得分:0)
你需要一个功能:
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))
输出:
('5', 'c')