![](/img/trans.png)
[英]Python print a list of strings horizontally without quotations or brackets
[英]How do I use zip print on a list of strings in python without it returning with quotations surrounding them?
當前代碼:
reps = ['x 5', 'x 5', 'x 3', 'x 5', 'x 5', 'x 5+']
b = [90, 122, 135, 146, 168, 191]
print(str(list(zip(b,reps))).replace(',',''))
這是當前的 output:
[(90 'x 5') (112 'x 5') (135 'x 3') (146 'x 5') (168 'x 5') (191 'x 5+')]
這是我的目標 output:
[(90 x 5) (112 x 5) (135 x 3) (146 x 5) (168 x 5) (191 x 5+)]
我將如何刪除那些單引號?
我嘗試使用替換,但我不確定如何替換分隔重量和重復次數的逗號,以及重復次數范圍內的引號。
我還嘗試用單獨的代碼行替換列表代表中的引號,但是一旦在 zip 中打印出來,它們就會被加回去。
這不是一件美麗的事情,但如果你唯一的目標是最終得到你指定的 output 那么這將做到這一點:
reps = ['x 5', 'x 5', 'x 3', 'x 5', 'x 5', 'x 5+']
b = [90, 122, 135, 146, 168, 191]
# creates a list of strings of the form: "(X x Y)"
arr = [f"({y} {x})" for x, y in zip(reps, b)]
# prints the list as a single string surrounded by brackets
print(f"[{' '.join(arr)}]")
Output:
[(90 x 5) (122 x 5) (135 x 3) (146 x 5) (168 x 5) (191 x 5+)]
這聽起來像是化妝品output,但以下內容適用於您的情況:
print('[' + ' '.join(f"({x} {y})" for x, y in zip(b, reps)) + ']')
[(90 x 5) (122 x 5) (135 x 3) (146 x 5) (168 x 5) (191 x 5+)]
如果你想要那種確切的格式,你可以使用
print(
str(list(map(lambda tup: f"({str(tup[0])} {tup[1]})",list(zip(b,reps))))).replace("'",'').replace(",",'')
)
print(str([f"({x} {y})" for x, y in zip(b, reps)]).replace(",", "").replace("'",""))
也許不是最有效的方法,但它確實有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.