问题
I have a string, dictionary in the form:
('(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)
}
)
Each parentheses is a tuple which corresponds to (score, standard deviation). I'm taking the average of just the first integer in each tuple. I've tried this:
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)
When I run:
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)})
I should get the average of only 'laughter'
and 'flower'
: 8.5 + 7.88 / 2
but this running function also includes 'laugh'
and 'flow'
: 8.5 + 7.88 + 9.5 + 2.3 /4
.
回答1:
@Ignaco is right about why you're including "flow" and "laugh"...
You could write the code as the following though:
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)
so you generalise the function to just average the first element of relevant keys:
def somefunc(keys, dct):
vals = [dct[k][0] for k in keys]
return sum(vals) / float(len(vals))
And you have to pre-process some string somehow, so that it's a sequence of valid keys:
some_string = '(laughter flower)'
keys = some_string[1:-1].lower().split()
print somefunc(keys, some_dict)
回答2:
something like this:
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
回答3:
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))
your string ='(Laughter flower)'
its a string not two different word so when u apply [d[word][0] for word in d if word in string] its not getting the word. so it will be easy if you donot use () parenthesis around your string. instead use 'Laughter flower'. but still its one string not two word so u have to split it string.split() and it will create a list of two words then your function will work.
来源:https://stackoverflow.com/questions/13006271/using-list-comprehension