以相反和特定格式打印列表中的元素

时间:2018-03-29 23:52:27

标签: python

我有一个包含以下内容的列表:

lst = [10,6,1] 

我现在要做的是以特定格式以相反的顺序打印列表元素。以下是我想要的输出:

Candidate: 1,6,10

基本上我想以相反的顺序打印出列表的元素以及字符串" Candidate"与它连接起来。我试过了:

lst = [10,6,1]
for i in range(len(lst)-1,-1,-1):
     print("Candidate: " + str(lst[i])

但我得到了:

Candidate: 1
Candidate: 6
Candidate: 10

而不是:

Candidate: 1,6,10

我很确定它是因为循环,循环遍历每个元素并打印出来导致新行,但是可以做些什么来实现我想要的输出?

4 个答案:

答案 0 :(得分:2)

列表理解是完美的,这也是我们喜欢Python XD的原因之一。

print("Candidate: " + ",".join([str(i) for i in my_list[::-1]))

答案 1 :(得分:2)

没有for循环的另一种解决方案。您只需要在sep打印功能中使用python 3参数。

print('Candidate: ', end='')
print(*reversed(l) , sep=',')

答案 2 :(得分:1)

使用 ImageView t1 = findViewById(R.id.t1); ImageView f1 = findViewById(R.id.f1); int tempt1 = t1.getSolidColor(); int tempf1 = f1.getSolidColor(); f1.setBackgroundColor(tempt1); t1.setBackgroundColor(tempf1); ,然后将其转换为列表。

reversed

<强>输出:

lst_rev = list(reversed(lst))
print("Candidate: "+ str(lst_rev)[1:-1])

答案 3 :(得分:0)

干净的方法是:

lst = [10,6,1]

reverse_=lst[::-1]
for i in reverse_:
    print("Candidate : {}".format(i))

outout:

Candidate : 1
Candidate : 6
Candidate : 10

只是为了好玩:

lst = [10,6,1]
print(list(map(lambda x:"Candidate : {}".format(x),lst[::-1])))

输出:

['Candidate : 1', 'Candidate : 6', 'Candidate : 10']