我创建了一组代码,可以将句子转换为位置列表。
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")
我需要代码能够为每个句子创建单独的列表,而不会对代码进行过多修改
答案 0 :(得分:0)
我认为你要找的是一个功能:
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语句是您在使用它时从函数中返回的内容。基本上,你传入一些值,做一些计算,然后吐出另一个值。