任何人都可以解释这行python代码吗? 'position = [s.index(x)+1 for s in s]'

时间:2016-05-18 10:48:09

标签: python

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

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()

我无法理解的是'position = [s.index(x)+1 for s in s]'有人可以解释一下吗?

2 个答案:

答案 0 :(得分:3)

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

positions = []

for x in s:
    positions.append(s.index(x)+1)

s.index()会在您的x字词列表中返回单词s的位置。

请注意,同一个单词的多次出现都将指向该单词的第一个索引。例如第二次出现"ASK"仍然会指向1

答案 1 :(得分:0)

嗨 - 翻译成人类,意味着将句子中每个单词的位置(+1)放在positions数组中。

positions = 让职位为:
{strong> [s.index(x) xs的索引,或sentence.split()
+1 在索引中添加一个,因为索引从大多数语言的0开始 for x in s] ,为s中的所有元素执行此操作。

如果代码如下所示,代码看起来会更好:

splitsentence = sentence.split()
positions = splitsentence.index(word)+1 for word in splitsentence

更长,但可读。