[英]How to use append() and make output of loop into new list instead of print
我正在使用一個循環,效果很好:
for i, line in enumerate(lines2):
if "2. Primary Contact Person" in line:
print(*lines[i:i+5], sep="\n")
這給了我回頭聯系信息。 到目前為止沒有問題。 但是我現在想打印出來並將其附加到新列表中,而不僅僅是打印它。
我試過了
primary_contact = []
for i, line in enumerate(lines2):
if "2. Primary Contact Person" in line:
primary_contact.append(*lines[i:i+5], sep="\n")
但是我收到以下錯誤:TypeError:append()不帶關鍵字參數
我如何將其輸出到列表中?
Python的list.append方法不需要其他命名參數。 方法append僅將要添加到列表末尾的元素作為參數。 就您而言,我相信它將是:
primary_contact.append(行)
根據上面的示例,取決於實際行的內容,列表切片可能適用於您希望附加的實際字符串。
使用列表推導:
primary_contact = ['\n'.join(lines[i:i+5]) for i, line in enumerate(lines2) if "2. Primary Contact Person" in line]
術語:
'\n'.join(lines[i:i+5])
生成與早期輸出等效的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.