简体   繁体   English

如何从同一行的两个列表中打印项目?

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

Really new to python, started today. python真的是新手,今天开始。 I got a list of verbs and nouns from a txt list, I loaded them in and I was trying to print a noun and verb together from a specific position in the list. 我从txt列表中获得了动词和名词的列表,将它们装入其中,并试图从列表中的特定位置一起打印名词和动词。 How do I make them print on the same line? 如何使它们在同一行上打印? they were printed on different lines. 它们被打印在不同的行上。

Here is my code: 这是我的代码:

    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])

You can use the zip method to iterate over multiple iterables. 您可以使用zip方法来迭代多个可迭代对象。

Example

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

returns 回报

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

Reading lines from a file includes the trailing newline. 从文件读取行包括尾随换行符。 So each noun in the list looks like "noun\\n". 因此,列表中的每个名词看起来都像“名词\\ n”。 When printing the noun, because the noun includes a new line at the end, it causes the verb to be on the next line. 在打印名词时,由于名词的末尾包括新行,因此使动词位于下一行。 What you want to do is remove the trailing newline. 您要做的是删除尾随的换行符。

To remove the trailing newline, use rstrip(). 要删除尾随的换行符,请使用rstrip()。

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

See this answer for more detail about rstrip. 有关rstrip的更多详细信息,请参见此答案。 https://stackoverflow.com/a/275025/6837080 https://stackoverflow.com/a/275025/6837080

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM