首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何打印一次克隆列表并在Python字典中加载?

如何打印一次克隆列表并在Python字典中加载?
EN

Stack Overflow用户
提问于 2016-09-24 08:04:48
回答 1查看 27关注 0票数 0
  1. 我的输入文件: cs 124456强cs 124456强我125454易我125455易我125455易ec 125555做ec 127678罚款ec 127678罚款ci 127678罚款eee 125678好eee 125678不好
  2. 预期产出: no.name reg执行1.cs 124456强大2.me 125454轻松3.me 125455轻松4.ec 125555做5.ec 127678罚款6.ci 127678罚款7.eee 125678好8.eee 125678坏
  3. 我的代码: 导入os os.chdir("d:/filer")导入re第一(行):f=re.findall(“a+”,line,flags=0)返回f def num(line):n=re.findall("\d{6}",line,flags=0)返回n带open("once.txt“),( "r")作为sa:对于sa.readlines()中的行: home=first( line ) number=num(line) x=home y=number z=home1,如果x!=0和y!=0,z!=0:打印x,y,z
  4. 我打开文件,一行行地读。然后,我使用正则表达式提取这些数字和文本,并将其存储在带有索引的列表中。现在我只想要唯一的列表,而不是克隆的。然后把它们装入字典。有人能帮我吗?
EN

回答 1

Stack Overflow用户

发布于 2016-09-24 12:21:18

为了防止克隆,您可以使用类似的set()

代码语言:javascript
运行
复制
results = set()  # Construct a set
 with open("once.txt","r") as sa:
     for line in sa.readlines():
          home=first(line)
          number=num(line)
          x=home[0]
          y=number[0]
          z=home[1]
          if x!=0 and y!=0 and z!=0:
            if (x,y,z) not in results:  # Check if the set already contains the result
                results.add((x,y,z))  # If it doesn't, add to the set and print.
                print [x,y,z]

我还建议稍微组织一下您的代码。您只需为清晰性创建1个正则表达式,如下所示:

代码语言:javascript
运行
复制
results = set()  # Construct a set
with open("once.txt","r") as sa:
    count = 0
    for line in sa:  # No need for readlines()
        match = re.match(r"(\w+)\s+(\d+)\s+(\w+)")

        if match is None:
            continue

        result = match.groups()
        if result not in results:  # Check if the set already contains the result
            count += 1
            results.add(result)  # If it doesn't, add to the set and print.
            print count, result
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39674028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档