有人能解释一下这行python代码吗';位置=[s.index(x)和s中x的#x2B;1]';

有人能解释一下这行python代码吗';位置=[s.index(x)和s中x的#x2B;1]';,python,Python,我无情地搜索了互联网。我知道总会有答案的。但是我找不到它。下面是代码(简而言之,我的代码将存储的数组更改为数字,然后将其保存为文本文件) sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" #Stores these words in the array s = sentence.split() #splits the variable 'sentence' into

我无情地搜索了互联网。我知道总会有答案的。但是我找不到它。下面是代码(简而言之,我的代码将存储的数组更改为数字,然后将其保存为文本文件)

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" #Stores these words in the array
s = sentence.split() #splits the variable 'sentence' into seperate words and stores them into the variable 's'
positions = [s.index(x)+1 for x in s]
print(sentence) #prints the variable 'sentence'
print(positions) #prints the variable 'positions'

sentence=str(sentence) #converts the variable 'sentence' into a string
positions=str(positions) #converts the variable 'positons' into a string

inputFile=open("thelist.txt","w") #
inputFile.write(sentence)
inputFile.write("\n")
inputFile.write(positions) 
inputFile.close()

我无法理解的一行是“positions=[s.index(x)+1代表s中的x]”有人能解释一下吗?

这是一个列表理解,相当于

positions = []

for x in s:
    positions.append(s.index(x)+1)
s.index()
返回单词
x
在单词列表
s
中的位置


请注意,同一单词的多次出现都将指向该单词的第一个索引。e、 g.
“ASK”
的第二次出现仍然指向
1

Hi–翻译为Human,它意味着将句子中每个单词的位置(+1)放在
位置
数组中

位置=
让位置为:
[s.index(x)
s
中的
x
索引,或
语句.split()

+1
在索引中添加一个,因为大多数语言的索引从0开始
用于s中的x]
并对
s中的所有元素执行此操作

如果代码看起来像:

SplitSession=句子.split()

positions=splitsequence。splitsequence中单词的索引(单词)+1


更长,但可读。

这与
范围(1,len)+1)有何不同?也许OP的目的正是检测复制品。谢谢!这真的很有帮助!!谢谢,我将尝试将其合并到我的代码中。尽量使变量名具有描述性。这很有帮助,而且当你的代码变得更大时,这是至关重要的。