I have a list of integers and I want to concatenate them in a loop.
This is what I have so far
a = [3, 4, 6]
temp = []
for i in a:
query = 'Case:' + str(i)
temp.append(query)
print(' OR '.join(temp))
>>> Case:3 OR Case:4 OR Case:6
Is there a better way to write this?
答案 0 :(得分:2)
Yes, you can use generator expression and str.join
,
' OR '.join('Case: {}'.format(i) for i in a)
Example/Demo -
>>> a = [3, 4, 6]
>>> ' OR '.join('Case: {}'.format(i) for i in a)
'Case: 3 OR Case: 4 OR Case: 6'
答案 1 :(得分:2)
You can also use map and lambda expressions:
temp = map(lambda x: 'Case: '+str(x), a)
答案 2 :(得分:1)
You could also use a comprehension:
>>> a = [3, 4, 6]
>>> ' OR '.join([ "Case " + str(x) for x in a ])
'Case 3 OR Case 4 OR Case 6'
答案 3 :(得分:0)
完成@Joshua K使用map和lambda的想法(尽管我认为列表理解是一个更好的解决方案):
>>> a = [3, 4, 6]
>>> 'OR '.join(map(lambda i: 'Case:' + str(i) + ' ', a))
Case:3 OR Case:4 OR Case:6