Python 将多个句子转换成不同的位置
我已经创建了一套代码,可以将句子转换成一系列位置Python 将多个句子转换成不同的位置,python,Python,我已经创建了一套代码,可以将句子转换成一系列位置 sentence = "ask not what you can do for your country ask what your country can do for you" d = {} i = 0 values = [] for i, word in enumerate(sentence.split(" ")): if not word in d: d[word] = (i + 1) values +=
sentence = "ask not what you can do for your country ask what your country can do for you"
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
print(values)
我现在需要的程序能够转换多个句子
是的
sentence = ("ask not what you can do for your country ask what your country can do for you")
sentence2 = ("some people enjoy computing others do not enjoy computing")
sentence3 = ("i will use this as my last sentence as i do not need another sentence")
我需要代码能够为每个句子创建单独的列表,而不需要对代码进行太多修改我认为您需要的是一个函数:
def get_positions(sentence):
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
return values
print get_positions(sentence1)
print get_positions(sentence2)
print get_positions(sentence3)
这样做的目的是创建一个函数,将一个句子作为参数,然后将其转换为您想要构造的列表。任何时候你想要得到一个句子的位置,你可以用你想要得到位置的句子作为参数调用你的函数
注意,我将代码末尾的打印更改为返回值。return语句是在使用函数时从函数返回的语句。基本上,你传入一些值,做一些计算,然后吐出另一个值