【问题标题】:Python - 'Subtract' Elements in 1 List From The End of The Elements in 2nd List. Elements are strings not integersPython - 从第 2 个列表中的元素末尾“减去”第 1 个列表中的元素。元素是字符串而不是整数
【发布时间】:2013-10-08 20:21:04
【问题描述】:

我是 python/编程新手。使用python 2.7

我一直试图弄清楚如何从另一个列表中的元素中“减去”一个列表中的元素。但是,我将“减”放在引号中,因为我不使用整数,并且想不出另一种解释方式。

首先,这是我的代码:

plural_string = "cell phones|sheep|oxen" # result of user input with raw_input()
plural_endings_string = "s,,en"                   # result of user input with raw_input() - always comma separated.  
plural_list = plural_string.split('|')
plural_endings_list = plural_endings_string.split(',')

# This is pseudo code since '-' does not work with non-integers in a string
# but it expresses what I am trying to achieve
new_list = [a - b for a, b in zip(plural_list, plural_endings_list)] 

所以,我真正希望新列表看起来像这样:

>>> new_list
>>> ['cell phone', 'sheep', 'ox']

我基本上想使用plural_endings_list 变量中的复数结尾(元素)对plural_list 变量中的单词(元素)进行去复数化。

需要注意的关键事项是: 列表中的元素数量(以及因此的单词选择)将根据用户输入(我)而有所不同。因此,在不同的情况下,我正在使用的列表可能如下所示:

plural_list = ['children', 'brothers', 'fish', 'penguins']
plural_endings_list = ['ren', 's', '', 's']

我试图弄清楚如何使用字符串(而不是列表)使用 '.replace' 函数来执行此操作,但我遇到了一堵砖墙,因为我不知道用户输入会做什么在脚本的每次运行中。我找不到“一刀切”的解决方案。也没有成功地尝试过正则表达式,并且遇到了同样的问题,即不知道用户输入是什么。它现在超出了我的新手大脑。

希望我已经清楚地解释了自己!如果不是,我试图在 SO - How do i add two lists' elements into one list? 中做与其他问题相反的事情 但是,我需要'减法'而不是串联

干杯 达伦

EDIT1:回应@brad 评论。实际上,我通过用户输入将复数结尾输入到plural_endings_list(这是更大脚本的一部分)。因此,如果列表包含元素"children's",那么我会选择"'s" 作为plural_endings_list 的结尾。它总是针对具体情况。

EDIT2:回应@Graeme Stuart 的评论。 Graeme - 输入的长度总是不同的。每个列表中可能有 2 个元素,或者每个列表中可能有 10 个元素,或者介于两者之间。

【问题讨论】:

  • 您想如何处理儿童案件?让它成为孩子的?也去掉's?

标签: python list list-comprehension


【解决方案1】:

我认为这可以满足您的需求。它虽然有点笨重。您的输入是否总是相同的长度?

def depluralise(plurals, plural_endings):
    new_list = []
    for plural, plural_ending in zip(plurals, plural_endings):
        if plural.endswith(plural_ending):
            if plural_ending == '':
                new_list.append(plural)
            else:
                new_list.append(plural[:-len(plural_ending)])
    return new_list 


plural_string = "cell phones|sheep|oxen"
plurals = plural_string.split('|')
plural_endings_string = "s,,en"
plural_endings = plural_endings_string.split(',')

print depluralise(plurals, plural_endings)

plurals = ['children', 'brothers', 'fish', 'penguins']
plural_endings = ['ren', 's', '', 's']

print depluralise(plurals, plural_endings)

【讨论】:

  • 感谢格雷厄姆,这非常适合我的需要。
【解决方案2】:
>>> p = 'children'
>>> e = 'ren'
>>> if p.endswith(e):
...   print p[:-len(e)]
... 
child

【讨论】:

    【解决方案3】:

    这可能不是您想要的答案,但为了获得最好的去复数化,您需要一本名词及其复数字典。

    搜索复数,并将其替换为单数。

    我认为这样做比尝试处理遇到的所有异常要少:

    • 女性
    • 现象
    • 数据
    • 骰子
    • ...

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 2015-02-10
      • 2019-01-08
      • 2015-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多