我有一个字典程序,但是输出结果时有问题,我要每个句子的结果。你知道吗
dict_file = """water=45
melon=8
apple=35
pineapple=67
I=43
to=90
eat=12
tastes=100
sweet=21
it=80
watermelon=98
want=70
juice=88"""
conversion = {k: int(v) for line in dict_file.split('\n') for (k,v) in (line.split('='),)}
text = """I want to eat banana and watermelon
I want drink juice purple and pineapple
it tastes sweet pineapple"""
result= ', '.join(str(conversion[word]) for word in text.split() if word in conversion)
print(result)
输出:
43, 70, 90, 12, 98, 43, 70, 88, 67, 80, 100, 21, 67
我想输出:
43, 70, 90, 12, 98
43, 70, 88, 67
80, 100, 21, 67
就个人而言,可读性比简洁更重要。你知道吗
text.split()
在所有空格上拆分,删除换行符。首先在换行符('\n'
)上拆分,然后在剩余的空白处拆分。用逗号重新连接你在空白处的内容。用换行符和换行符重新连接拆分的内容。你知道吗如果更改
conversion
的定义,可以将str(conversion[word])
更改为conversion[word]
:我更喜欢这样的定义:
以下是一个不同的变体,它以不同的方式处理缺少的值:
print(result)
给出相关问题 更多 >
编程相关推荐