简体   繁体   English

Python使用字符串格式运算符打印两个列表

[英]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)))
  • zip(a, b) would return pairs from both lists until shorter list is over zip(a,b)将从两个列表中返回对,直到较短的列表结束
  • map(f, a) would apply function f to every element in list a. map(f,a)将函数f应用于列表a中的每个元素。
  • join is a python way to concatenate strings join是连接字符串的python方法

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.

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