Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将数组位置中的字符串转换为位置并返回python中的顺序_Python - Fatal编程技术网

将数组位置中的字符串转换为位置并返回python中的顺序

将数组位置中的字符串转换为位置并返回python中的顺序,python,Python,我一直在使用列表和数组。在这个任务中,我需要返回(按顺序)句子,但不是按顺序返回句子,而是按顺序返回单词所在的位置,因此这是我当前的代码: sentence = "Hello my name is Daniel, hello Daniel" sentence = sentence.upper() sentence = sentence.split() list = sentence 返回: ['HELLO', 'MY', 'NAME', 'IS', 'DANIEL,', 'HELLO', 'D

我一直在使用列表和数组。在这个任务中,我需要返回(按顺序)句子,但不是按顺序返回句子,而是按顺序返回单词所在的位置,因此这是我当前的代码:

sentence = "Hello my name is Daniel, hello Daniel"
sentence = sentence.upper()
sentence = sentence.split()
list = sentence
返回:

['HELLO', 'MY', 'NAME', 'IS', 'DANIEL,', 'HELLO', 'DANIEL']
但预期的结果是:

[0, 1, 2, 3, 4, 0, 4]

有人知道我如何通过向给定代码添加更多代码来获得此结果吗?

似乎您希望获得
Daniel
而不是
Daniel,
因此您应该替换逗号或删除它。然后使用index方法返回obj出现的列表中的最低索引

sentence = "Hello my name is Daniel, hello Daniel"
sentence = sentence.replace(',','').upper()
sentence = sentence.split()


print [sentence.index(i) for i in sentence]
它回来了

[0, 1, 2, 3, 4, 0, 4]

似乎您希望获得
Daniel
而不是
Daniel,
,因此您应该替换逗号或删除它。然后使用index方法返回obj出现的列表中的最低索引

sentence = "Hello my name is Daniel, hello Daniel"
sentence = sentence.replace(',','').upper()
sentence = sentence.split()


print [sentence.index(i) for i in sentence]
它回来了

[0, 1, 2, 3, 4, 0, 4]

在您的模型中,
'DANIEL'
'DANIEL'
都用
4
表示。您需要去除标点符号吗?@mgilson在本例中,标点符号不会影响结果,因此“Daniel”和“Daniel”被视为相同的,并且应该在您的模型中返回相同的位置,
“Daniel”、“Daniel”和
“Daniel”
都由
4
表示。你需要去掉标点符号吗?@mgilson在这种情况下标点符号不会影响结果,因此“Daniel”和“Daniel”被视为相同的,应该返回相同的位置谢谢!!!如果变量“句子”是用户输入的句子,此方法是否有效?@D.Forrester yeah。如果有帮助,请接受此答案。句子=句子。替换(“,”,“,”,“”)”)。上限()AttributeError:“list”对象没有属性“replace”。当我在用户输入的变量中造句时,出现了此错误。您知道原因吗@McGrady@D.Forrester确保
句子
是字符串,然后使用
split()
method。要将输入作为字符串获取,您应该在Python2中使用
raw\u input
,或者在Python3中使用
input
。谢谢!!!如果变量“句子”是用户输入的句子,此方法是否有效?@D.Forrester是的。如果这有帮助,请接受此答案。句子=句子。替换(“,”,“,“,”,“,”)”)”)。upper()AttributeError:“list”对象没有属性“replace”。当我在用户输入的变量中造句时,出现了此错误。你知道为什么吗@McGrady@D.Forrester确保
句子
是字符串,然后使用
split()
方法。要将输入作为字符串获取,应在Python2中使用
raw\u input
,或在Python3中使用
input