Python 连接两个子列表

Python 连接两个子列表,python,arrays,Python,Arrays,社区 我正在努力添加从文本文件中提取的两个子列表(p和t)。代码在“print(p,t)”之前应该是正常的,但是之后的append命令不起作用(我也尝试了output.extend([p,t]))。名单包括: p=代词(由受试者说出) t=测试人员(用VP+数字缩短) 更棒的是,不仅要得到代词,还要得到它出现的行,不幸的是,在当前代码中,这不起作用。 我还得到了一个缩进错误,而我的同事使用相同的代码却没有得到 谢谢大家! import re with open (r'./Transli

社区

我正在努力添加从文本文件中提取的两个子列表(p和t)。代码在“print(p,t)”之前应该是正常的,但是之后的append命令不起作用(我也尝试了output.extend([p,t]))。名单包括: p=代词(由受试者说出) t=测试人员(用VP+数字缩短) 更棒的是,不仅要得到代词,还要得到它出现的行,不幸的是,在当前代码中,这不起作用。 我还得到了一个缩进错误,而我的同事使用相同的代码却没有得到

谢谢大家!

import re

    with open (r'./Transliteration_Task1_DE.txt', 'r')as file:

        pro=["ich", "mir", "mich", "wir", "uns", "du", "dir", "dich"]
        t=""    #variable for testpersons
        output=list()
        for line in file:
            words=list()
            words=line.split(" ")
            #print(words)
            if re.match(r'.*VP.*', line):
                t=line
                words=line.split(" ")
                #print(words)
            for w in words:
                #print(w)
                for p in pro:
                    if p == w:
                        print(p, t)
                        output.append([p,t])
        for o in output:
            print(output) #output should be a list with sublists (testpersons and pronouns)

您的代码可以简化:

pronouns = ["ich", "mir", "mich", "wir", "uns", "du", "dir", "dich"]
output = []

with open (r'./Transliteration_Task1_DE.txt', 'r') as file:
    for line_number, line in enumerate(file):
        words = line.split()  # Split the line on whitespaces such that words contains a list of words from the line.

        if "VP" in line:  # Only do something if the line contains "VP" - you don't need a regular expression.
            for pronoun in pronouns:  # Search all pronouns
                if pronoun in words:  # If the pronoun is in the list of words, append it to the output
                    print(pronoun, line_number, line)
                    output.append([pronoun, line_number, line])

for o in output:
    print(o)
要获取行号,只需枚举文件句柄即可

要查看该行是否包含字符串
VP
,可以使用
in
操作符中的
,这是一种更类似于python的方法

类似地,对于第二个嵌套for循环:只需在
中使用
,查看代词是否包含在单词列表中

此外,它还有助于提供更可读的变量名。一个字符的名称常常令人困惑,而且很难阅读


此外,请记住,输入行可能包含需要删除的标点或大小写组合。如果您希望不区分大小写,则需要将所有单词都设置为小写(请参阅
str
lower
函数)。

如果您希望这样做,可以使用
+
运算符将两个列表合并:

>>> p = [0, 1]
>>> q = [2, 3]
>>> p + q
[0, 1, 2, 3]
使用
*
(星号)一元运算符解压缩元素:

>>> [*p, *q]
[0, 1, 2, 3]
并使用
.extend()
列表方法:

>>> p.extend(q)
>>> print(p)
[0, 1, 2, 3]

缩进错误通常是由制表符/空格的混合造成的。您正在使用什么文本编辑器?你只需要做一个循环-你可以把
的words中的w:pro中的p:if p==w:
更改为
的words中的w:if w in pro:
请举例说明你是什么expecting@Kind陌生人谢谢你!我正在使用记事本++。我想得到一个输出,上面写着:参与者,pro出现的行。例如VP1,“我的法律不适用”;在这种情况下,您应该能够单击
¨
按钮来显示所有字符。确保使用制表符或空格(不要混用),并确保它们都对齐。如果提供示例输入,则输出您期望的内容。那太好了。