使用列表理解

时间:2012-10-22 06:53:18

标签: python string list dictionary tuples

我有一个字符串,字典:

('(Laughter flower)',
 {'laughter': (8.5, 0.9313),
  'flower': (7.88, 1.1718),
  'the': (4.98, 0.9145),
  'puppy': (7.58, 1.4581),
  'died': (1.56, 1.198),
  'laugh': (9.5, 0.1),
  'flow': (2.3, 0.51)
 }
)

每个括号都是一个元组,对应于(得分,标准偏差)。我取每个元组中第一个整数的平均值。我试过这个:

def score(string, d):
    if len(string) == 0:
        return 0
    string = string.lower()
    included = [d[word][0]for word in d if word in string]
    return sum(included) / len(included)

当我跑步时:

print score ('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower': 
(7.88, 1.1718), 'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581), 
'died':(1.56, 1.198),'laugh': (9.5, 0.1),'flow': (2.3, 0.51)})

我应该只获得'laughter''flower' 8.5 + 7.88 / 2的平均值,但此运行功能还包括'laugh''flow'8.5 + 7.88 + 9.5 + 2.3 /4

3 个答案:

答案 0 :(得分:2)

@Ignaco对你为什么要包括“流”和“笑”是正确的......

您可以按以下方式编写代码:

data = ('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower': (7.88, 1.1718), 
'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581), 'died':(1.56, 1.198), 'laugh': 
(9.5, 0.1),'flow': (2.3, 0.51)})

# Unpack for naming
keys, vals = data
# Assume () and first and last
look_for = keys[1:-1].lower().split()
# Get relevant numbers
nums = [vals[k][0] for k in look_for]
# Print average
print sum(nums) / len(nums)

所以你将函数推广到只是平均相关键的第一个元素:

def somefunc(keys, dct):
    vals = [dct[k][0] for k in keys]
    return sum(vals) / float(len(vals))

你必须以某种方式预先处理一些字符串,这样它就是一系列有效的密钥:

some_string = '(laughter flower)'
keys = some_string[1:-1].lower().split()
print somefunc(keys, some_dict)

答案 1 :(得分:1)

类似的东西:

In [65]: lis=('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower': (7.88, 1.1718), 
'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581), 'died':(1.56, 1.198), 'laugh': 
(9.5, 0.1),'flow': (2.3, 0.51)})

In [68]: strs=lis[0].strip('()').split() # returns ['Laughter', 'flower']

In [69]: lis1=[lis[1][x][0] for x in lis[1] if x in map(str.lower,strs)]

In [70]: sum(lis1)/float(len(lis1))
Out[70]: 8.1899999999999995

答案 2 :(得分:0)

def score(string,d):
    if string=="":
        return 0
    string=string.lower().split()
    included=[d[word][0] for word in d if word in string]
    return(sum(included)/len(included))

你的字符串='(笑声花)'

它的字符串不是两个不同的字,所以当你申请时 [d [word] [0]代表d 中的单词如果字符串中的单词 它没有得到单词。 所以如果你不在字符串周围使用()括号,那将很容易。 而是使用'笑声花'。 但仍然只有一个字符串而不是两个字,所以你必须把它分开 string.split() 它会 创建一个包含两个单词的列表,然后您的函数将起作用。

相关问题