簡體   English   中英

如何從同一行的兩個列表中打印項目?

[英]How to print items from two lists on the same line?

python真的是新手,今天開始。 我從txt列表中獲得了動詞和名詞的列表,將它們裝入其中,並試圖從列表中的特定位置一起打印名詞和動詞。 如何使它們在同一行上打印? 它們被打印在不同的行上。

這是我的代碼:

    f = open('/User/Desktop/Python/nouns/2syllablenouns.txt', 'r')
nouns = []
for l in f:
    nouns.append(l)

f = open('/User/Desktop/Python/verbs/2syllableverbs.txt', 'r')
verbs = []
for l in f:
    verbs.append(l)

print(nouns[1] + verbs[1])

您可以使用zip方法來迭代多個可迭代對象。

data1 = ["a", "b", "c"]
data2 = ["d", "e", "f"]
for a, b in zip(data1, data2):
    print("a: {0}, b: {1}".format(a, b))

回報

a:a,b:da:b,b:ea:c,b:f

從文件讀取行包括尾隨換行符。 因此,列表中的每個名詞看起來都像“名詞\\ n”。 在打印名詞時,由於名詞的末尾包括新行,因此使動詞位於下一行。 您要做的是刪除尾隨的換行符。

要刪除尾隨的換行符,請使用rstrip()。

for l in f:
    nouns.append(l.rstrip())

有關rstrip的更多詳細信息,請參見此答案。 https://stackoverflow.com/a/275025/6837080

暫無
暫無

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

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