2013-10-08 61 views
0

我是python /编程新手。使用python 2.7Python - 从第二列表中的元素末尾开始的1列表中的'减去'元素。元素是字符串不是整数

我一直想弄清楚如何从另一个列表中的元素中“减去”1列表中的元素。不过,我把“减法”放在引号中,因为我不是用整数工作的,也想不出另一种解释方式。

一起来,这里是我的代码:

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变量。

需要注意的一个关键是:列表中的元素数量(因此,单词选择)将根据用户输入(me)而有所不同。所以,在不同的情况下,我与工作表看起来是这样的:

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

我试图找出如何使用字符串来做到这一点 - 而不是列表 - 使用“.replace”功能,但是我碰到了一堵砖墙,因为我不知道脚本每次运行时用户输入的内容。我找不到'1适合所有'的解决方案。尝试使用正则表达式也没有成功,并且遇到了不知道用户输入是什么的问题。现在超出​​了我的新手大脑。

希望我已经清楚地解释了我自己!如果不是我试图做所以这另一个问题的反面 - How do i add two lists' elements into one list? 但是,而不是串联,我需要“减法”

干杯 达伦

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

EDIT2:回复@Graeme Stuart评论。格雷姆 - 输入的长度总是不一样。每个列表中可能有2个元素,或者每个列表中可能有10个元素,或者其中任何元素。

+0

你想如何处理像儿童的案件?让它成为孩子的?解雇他们? – Brad

回答

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) 
+0

谢谢格雷厄姆,这对我所需要的完美工作。 –

1
>>> p = 'children' 
>>> e = 'ren' 
>>> if p.endswith(e): 
... print p[:-len(e)] 
... 
child 
0

这可能不是你想要的答案,但要获得最好去多元化,你想要的名词及其复数的字典。

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

我倒是觉得你少扯头发,这样做比试图处理所有的异常你会碰到这样:

  • 女性
  • 大雁
  • 现象
  • 数据
  • 骰子
  • ...
相关问题