![](/img/trans.png)
[英]In Python, is there a method to print lists into a string using .format notation?
[英]Python print two lists with string format operator
如何編寫python scrip解決此問題?
l=[1,2,3] Length A
X=[one,two,three,.... ] length A
如何打印/寫入文件輸出應該是
1=one 2=two 3=three ....
嘗試使用類似的東西,但是由於長度A是可變的,因此將不起作用
logfile.write('%d=%s %d=%s %d=%s %d=%s \n' % (l[1], X[1],l[2,X[3],l[4],X[4]))
使用zip
:
l = [1, 2, 3]
X = ['one', 'two', 'three']
' '.join('{}={}'.format(first, second) for first, second in zip(l, X))
輸出:
'1=one 2=two 3=three'
您還可以使用fString使其更簡潔:
numbers = [1, 2, 3]
strings = ['one', 'two', 'three']
print(' '.join(f'{n}={s}' for n,s in zip(numbers,strings)))
總計:
print(''.join(map('{}={}'.format, zip(l, X))))
print(''.join(map('='.join, zip(map(str,l), X))))
由於join僅適用於字符串,因此map(str,l)將[1、2 ...]轉換為['1','2',..]
格式適用於任何輸入,因此不需要額外的轉換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.