使用列表理解

2024-04-16 13:00:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,字典的形式是:

('(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。你知道吗


Tags: thestringifflowword平均值元组score
3条回答

@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)

像这样:

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
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中的单词,如果字符串中的单词则不获取该单词。 因此,如果您不在字符串周围使用()括号,就很容易了。 取而代之的是“笑花”。 但是它仍然是一个字符串而不是两个单词,所以你必须拆分它字符串。拆分()它会 创建一个包含两个单词的列表,然后你的函数就可以工作了。你知道吗

相关问题 更多 >