[英]Python print two lists with string format operator
How do I write python scrip to solve this? 如何编写python scrip解决此问题?
l=[1,2,3] Length A
X=[one,two,three,.... ] length A
how do print/write to file output should be 如何打印/写入文件输出应该是
1=one 2=two 3=three ....
Trying to use something like but since the Length A is variable this won't work 尝试使用类似的东西,但是由于长度A是可变的,因此将不起作用
logfile.write('%d=%s %d=%s %d=%s %d=%s \n' % (l[1], X[1],l[2,X[3],l[4],X[4]))
Use zip
: 使用
zip
:
l = [1, 2, 3]
X = ['one', 'two', 'three']
' '.join('{}={}'.format(first, second) for first, second in zip(l, X))
Output: 输出:
'1=one 2=two 3=three'
You could also use an fString to make this more concise: 您还可以使用fString使其更简洁:
numbers = [1, 2, 3]
strings = ['one', 'two', 'three']
print(' '.join(f'{n}={s}' for n,s in zip(numbers,strings)))
All combined: 总计:
print(''.join(map('{}={}'.format, zip(l, X))))
print(''.join(map('='.join, zip(map(str,l), X))))
since join works on strings only, map(str,l) convert [1, 2,..] to ['1', '2', ..] 由于join仅适用于字符串,因此map(str,l)将[1、2 ...]转换为['1','2',..]
format works on any input, so extra conversion is not required 格式适用于任何输入,因此不需要额外的转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.