如何创建另一个列表python的重复列表

时间:2019-08-27 09:36:06

标签: python

主要问题是效率和创造骗局。

如何使用另一个列表中的每个重复项创建文件/列表/任何容器?

示例输入: 2个列表:

names = ['brian','adam','mickey','brian','mouse','barbara','mouse']

files = ['明智的布莱恩','无趣的adam','肥胖的米奇','布莱恩 智能”,“鼠标notmikey”,“芭芭拉·斯玛蒂”,“鼠标clicknotclik”]

我尝试过方法:

    for name in names:
        for j in range(len(names)):
            if not names.index(name)==j:
                if name == names[j]:
                    number = names.index(name)
                    a = open(title + ".txt", 'a')
                    a.write('\n' + str(files[number]) + str(files[j])+'\n')
                    a.close()

它奏效了,但实际上并没有效率。我得到了重复的输出。

名称和文件类型为列表。

名称包含一个字,而文件包含此名称和一些数据

我需要在名称中找到相同的名称​​(这就是为什么我在名称中创建另一个名为名称的列表)的原因,当找到它时,它应该使用列表 files <中的全部数据创建一个txt / em>。

我知道这很复杂,但是我确实试图明确目标。

编辑:

好的,所需的输出是:

brian the wise
brian the intelligent

mouse notmikey
mouse clicknotclik

当实际输出为:

brian the wise
brian intelligent

brian the wise
brian intelligent

mouse notmikey
mouse clicknotclik

mouse notmikey
mouse clicknotclik

我知道这是因为它正在检查第二个Brian,但是如果它找到它,我希望它只写一次。

2 个答案:

答案 0 :(得分:0)

您可以使用理解列表来实现

这将尝试查看files的每个元素是否包含来自names的至少一个元素。

list(set())清除重复项


with open(title + '.txt', 'a') as f:
    [f.write("\n{}\n".format(entry)) for entry in files for name in list(set(names)) if name in entry] 

没有理解列表:



with open(title + '.txt', 'a') as f:
   for name in list(set(names)):
      for entry in files:
          f.write("\n{}\n".format(entry)) 

答案 1 :(得分:0)

您可以将名称的所有索引存储到字典中,并仅将“信息”重复项写入文件:

names = ["brian", "adam", "mickey", "brian", "mickey", "mouse", "brian"]
files = ["brian the wise", "adam not interesting", "mickey the fatty", "brian intelligent",
         "mickey the creepy", "mouse notmikey", "brian the mad"]
title = "omg_what_a_weird_task"

with open(title + ".txt", "a") as f:
    tmp = {}
    for i, name in enumerate(names):
        if name not in tmp:
            tmp[name] = [i]
        else:
            tmp[name].append(i)
    for name, indexes in tmp.items():
        if len(indexes) > 1:
            f.write("\n".join(files[i] for i in indexes))
            f.write("\n")