【问题标题】:Compare each item in a list with all previous items, print only unique items将列表中的每个项目与之前的所有项目进行比较,仅打印唯一项目
【发布时间】:2012-05-04 12:39:40
【问题描述】:

我正在使用以下正则表达式来匹配所有出现的特殊数字:

^([0-57-9]|E)[12][0-9]{3}[A-Z]?[A-Z]([0-9]{3}|[0-9]{4})

假设这个正则表达式匹配以下五个数字:

31971R0974
11957E075
31971R0974-A01P2
31971R0974-A05
51992PC0405

然后使用以下代码打印这些匹配项。这将打印列表中的每个项目,如果项目包含破折号,则破折号之后的所有内容都将被丢弃。

def number_function():

    for x in range(0, 10):

    print("Number", number_variable[x].split('-', 1)[0])

但是,这将打印五行,其中第 1、3 和 4 行相同。

我需要你的帮助来编写一个脚本,它将每个项目与所有以前的项目进行比较,并且只在项目不存在时打印它。

因此,所需的输出将是以下三行:

31971R0974
11957E075
51992PC0405

编辑2:

我解决了!我只需要四处走动。这是成品:

def instrument_function():
    desired = set()

    for x in range(0, 50):
        try:
            instruments_celex[x]
        except IndexError:
            pass
        else:
            before_dash = instruments_celex[x].split('-', 1)[0]
            desired.add(before_dash)        

    for x in desired:
        print("Cited instrument", x)

【问题讨论】:

  • 项目的顺序是否相关?
  • @Tim:不,项目的顺序不相关。

标签: regex python-3.x comparison


【解决方案1】:

到目前为止,我几乎没有做过 python,但这可能会满足你的需求

def number_function():
    desired = set()
    for x in range(0, 10):
        before_hyphen = number_variable[x].split('-', 1)[0]
        desired.add(before_hyphen)
    for x in desired:
        print("Number", x)

【讨论】:

  • 一个范围变量而不是循环遍历列表? -1
  • @LennartRegebro 指的是在 for 循环中使用 range,而在 Python 中编写它的正确方法是 for x in number_variable:,在循环体中使用 before_hyphen = x.split(..)。
  • 我只是直接使用了提问者的例子,我怎么知道提问者可能想要每个项目而不是前 10 个?
【解决方案2】:

这是您的“已完成”功能的一个版本,它更合理。

# Don't use instruments_celex as a global variable, that's terrible. 
# Pass it in to the function instead:
def instrument_function(instruments_celex): 
    unique = set()
    # In Python you don't need an integer loop variable. This is not Java.
    # Just loop over the list:
    for entry in instruments_celex:
       unique.add(entry.split('-', 1)[0])

    for entry in unique:
        print("Cited instrument", entry)

您还可以使用生成器表达式来缩短它:

def instrument_function(instruments_celex): 
    unique = set(entry.split('-', 1)[0] for entry in instruments_celex)
    for entry in set:
       print("Cited instrument", entry)

就是这样。实际上它非常简单,除非我在程序中至少执行两次,否则我不会单独创建它的功能。

【讨论】:

  • 吹毛求疵:你可能想要for entry in unique,而你所谓的“列表理解”实际上是一个生成器表达式。
  • @dbaupp:第一个不是挑剔的,谢谢。是的,你是对的,它是一个生成器表达式。这是一个挑剔的,但无论如何我都会改变它。准确地说总是更好。 :-)
猜你喜欢
  • 2020-10-16
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2021-09-06
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
相关资源
最近更新 更多