簡體   English   中英

Python使用字符串格式運算符打印兩個列表

[英]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)))
  • zip(a,b)將從兩個列表中返回對,直到較短的列表結束
  • map(f,a)將函數f應用於列表a中的每個元素。
  • join是連接字符串的python方法

總計:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM