在两个列表中找到UnRepeated字

时间:2017-07-17 21:15:52

标签: python

我在两个列表中有不同的单词,我也有一个提交词 我需要在两个列表中找出不同的单词 例如列表一:

apple
cut
chance

列出两个:

apple
cut
chance
help
there

我的镜头没有工作它给了我重复和没有重复的话 我的剧本

wcode = open('wcode.txt', 'r')
rcode = open('rcode.txt', 'r')
for new in wcode :
    if wcode.read() in rcode.read() :
        print(' Repeated ')
    else :
        print(' UnRepeated !!!' + '\n' + new)

2 个答案:

答案 0 :(得分:0)

听起来你想要两个列表之间的symmetric difference。为了找到这个,我会使用Python的set操作。

在将您的文件内容读入列表后,您可以将它们转换为集合并计算对称差异,如下所示。最后,如果需要,可以将结果转换回列表。

wcode = ['a', 'list', 'of', 'words', 'that', 'you', 'read', 'from', 'wcode', 'txt']
rcode = ['a', 'list', 'of', 'words', 'that', 'she', 'read', 'from', 'rcode', 'txt']
wcode = set(wcode)
rcode = set(rcode)

difference = wcode.symmetric_difference(rcode)

assert difference == {'she', 'you', 'wcode', 'rcode'}
final_result = list(difference)

答案 1 :(得分:0)

使用套装:

s1 = {"apple", "cut", "chance"}
s2 = {"apple", "cut", "chance", "help", "there"}

print("Repeated: " + ", ".join(s1 & s2))
print("Not repeated: " + ", ".join(s1.symmetric_difference(s2)))

修改

更大的问题是你应该以非常不同的方式使用你的文件:

wcode, rcode = (set(open(fn, "rb").read().splitlines()) for fn in [
    "rcode.txt",
    "wcode.txt"])