簡體   English   中英

如何在python列表中的每個元素中插入新行

[英]How to insert a new line to each element in a list in python

樣本輸出:

[
     '----',
     'S',
     'the friends are sitting in the little chicken cafe together after happily having submitted 
      their assignment 3. This is the most convenient spot for them and was where they worked on 
      the assignment together. Feeling their caffeine levels dropping below optimal, someone heads 
      to the counter and offers to buy everyone a coffee. Many seconds pass while waiting in line 
      (at least seven!) before they reach the front only to discover they left their wallet at 
      home. They decide to...',
     '====',
     '1. [diplomacy 5] use their diplomacy skills to request ask for a freebie -1 +2',
     '2. [acumen 4] draw on all their internal acumen to *will* a coffee into existence ++3 +4-1',
     '3. [acrobatics 3] use their acrobatics skills to dash home and return with their wallet 
      before the other patrons are the wiser +5 -E~1',
     '4. give up and return to the table -E~1'
]

我的代碼:打開(文件名,“r”)作為文件:

    my_list = file.read().splitlines()

我的代碼輸出:

['----','S','the friends are sitting in the little chicken cafe together after happily having submitted their assignment 3. This is the most convenient spot for them and was where they worked on the assignment together. Feeling their caffeine levels dropping below optimal, someone heads to the counter and offers to buy everyone a coffee. Many seconds pass while waiting in line (at least seven!) before they reach the front only to discover they left their wallet at home. They decide to...','====','1. [diplomacy 5] use their diplomacy skills to request ask for a freebie -1 +2','2. [acumen 4] draw on all their internal acumen to *will* a coffee into existence ++3 +4 -1','3. [acrobatics 3] use their acrobatics skills to dash home and return with their wallet before the other patrons are the wiser +5 -E~1','4. give up and return to the table -E~1']

我的問題是,我怎樣才能在下一個元素之前用一個新行輸出列表中的每個元素。

我嘗試使用 "\n".join() 但輸出沒有列表中每個元素的引號

with open (filename, "r") as file:
    my_list = file.read().splitlines()
    my_list = list(map(lambda s: s + '\n', my_list))

試試這個。

要獲得所需的漂亮打印輸出,請將每個字符串的repr打印在單獨的行上:

print('[')
for line in my_list:
    print(repr(line))
print(']')

通過使用pprint進行漂亮打印,您可以獲得類似但更緊湊的表示:

from pprint import pprint

pprint(my_list, indent=4)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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