[英]How to use one print() in python to print list items line by line - not in one streak?
[英]Print f list items in one line
我想在一行中打印列表。 我使用簡單的打印,但它在打印時不起作用。 請問我該怎么做? 謝謝
list = ["A", "B", "C"]
print(*[n for n in list], sep=", ")
print(f"Item was added: {*[n for n in nazvy]}")
使用' '.join
l = ["A", "B", "C"]
print(', '.join(l))
print(f"Item was added: {', '.join(l)}")
Output
A, B, C
Item was added: A, B, C
注意:盡量不要使用內置關鍵字作為變量名。 例如: list
您的代碼不起作用,因為 f-string 不允許星號表達式或解包。
同時
print(*[n for n in list], sep=", ")
工作,因為它轉換到下面由於列表拆包
print('A', 'B', 'C', sep=", ")
我建議這樣做:
list = ["A", "B", "C"]
print(f'Item was added: {",".join(str(x) for x in list)}')
print(f'Item was added: {", ".join(str(x) for x in list)}')
根據對這個問題的公認答案: f-string syntax for unpacking a list with括號抑制
使用 "end=" 而不是 "sep=";
list = ["A", "B", "C"]
for x in list:
print(x, end=', ')
您可以使用*list
將每個值發送到打印語句。 使用這種方法,您不必擔心將數據轉換為字符串。
有了這個,你可以給
mylist = ["A", "B", "C", 4, 5, 6]
print(*my_list, sep=", ")
output 將是:
A, B, C, 4, 5, 6
如果你想使用 fstring,你也可以嘗試給出:
print(f'{*mylist,}')
output 將是:
('A', 'B', 'C', 4, 5, 6)
請注意,它使用方括號()
打印。
有關解壓 f-string 的更多詳細信息,請參閱此處Stackoverflow 上的帖子
另外請盡量避免將變量命名為list
。 稍后當您要將數據轉換為列表時,它會變得混亂。
例子:
x = {1:5,2:10,3:15}
y = list(x)
print (y)
將字典x
轉換為列表y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.