python用另一个lis检查列表

2024-04-26 20:41:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件:

file A:
U1
U2
U3
file B:
U1hjg 444 77 AGT
U8jha 777 33 AKS
U2jsj 772 00 AKD
U55sks 888 02 SJD
U3jsj 666 32 JSJ

我有两张单子:

listA=open("file A").readlines()
listB=open("file B").readlines()

我想检查listA的每个成员是否存在于列表B中,并打印两个文件:一个是带有匹配项的文件B(由listA排序),另一个是不带匹配项的文件B。 期望输出:

file list_match:
U1hjg 444 77 AGT
U2jsj 772 00 AKD
U3jsj 666 32 JSJ

file list_unmatched:
U8jha 777 33 AKS

U55sks 888 02 SJD型

我是一个非常初学者,所以我开始尝试这个例子:

print(ListA[1])
print(ListB[2])

if ListA[1] in ListB[2]:
    print("yes")

输出为:

U2
U2jsj 772 00 AKD

但是“是”没有打印出来

但如果我这么做了:

if "U2" in ListB[2]:
    print("yes")

输出为:

yes

我不明白错误在哪里。有人能帮我吗


Tags: 文件aksyesfileprintlistau2listb
2条回答

这是因为readlines()给您一行以\n结尾的字符。因此,当你

if ListA[1] in ListB[2]:
    print("yes")

您实际上是在检查"U2\n"是否在"U2jsj 772 00 AKD\n"中,这将返回False。但由于"U2"实际上是存在的,所以当您使用文字时,它会打印"yes"

您可以在下面的示例程序中验证这一点:

$ cat text.txt 
Sample
Text
Here.
$ cat test.py
with open("text.txt", "r") as f:
    text = f.readlines()
    print text
    print text[0]
$ python test.py
['Sample\n', 'Text\n', 'Here.\n']
Sample

$ #prompt

要纠正这个问题,如果文件太大,请使用ListA[1].rstrip()剥离行

否则,您可以使用.read()并在"\n"上拆分,创建列表,并使用自定义列表理解方法:

with open("file A") as f1 ,open("file B")  as f2:
    s1 = f1.read().split("\n")
    s2 = f2.read().split("\n")
    with open("matching.txt","w") as match, open("non-matching.txt","w") as no_match:
        matching = [x for x in s2 for y in s1 if y in x]
        non_matching = [x for x in s2 for y in s1 if y not in x]
        for line in matching:
            match.write(line)
        for line in non_matching:
            no_match.write(line)
st = set(list_b)

matches  = ([line for line in list_a if line  in st])

要同时获得:

# with will close your file automatically
with open("file A") as f1 ,open("file B")  as f2:
    st = set(f2) # get set of all lines in file b
    matches = []
    diff = []
    for line in f1: # iterate over every line in file a
        if line in st: # if line is in file b add it to our matches
            matches.append(line)
        else: # else add it to our diff list
            diff.append(line)

如果要创建两个新文件而不是附加到列表中,只需编写行即可

with open("file A") as f1,open("file B") as f2,open("matches.txt","w") as mat ,open("diff.txt","w") as diff:
    st = set(f1) 
    for line in f2:
        if line in st:
            mat.write(line)
        else:
            diff.write(line)

您只需要在自己的示例中使用ListA[1].rstrip() in ListB[2]。在ListA[1]和除最后一行以外的所有行的末尾有一个换行符。 如果你print(repr(ListA[1])),你会看到那里到底有什么

当我们迭代时,打印我们的集合和每一行,您可以在末尾看到换行符:

{'U2\n', 'U3', 'U1\n'} <-st
#  print(repr(line)) on all lines from fileB
'file B:\n'
'U1hjg 444 77 AGT\n'
'U8jha 777 33 AKS\n'
'U2jsj 772 00 AKD\n'
'U55sks 888 02 SJD\n'
'U3jsj 666 32 JSJ'

相关问题 更多 >