列表及其位置

时间:2016-05-06 11:12:24

标签: python list

我正在创建一个输入句子的代码,它会将句子中的每个单词拆分成一个单独的成员。当我输入一个单词并再次输入时,这两个单词将在下面显示相同的单词。例如,

This is a This is a 
 1   2  3  1    2 3

问题是,我的代码以不同的方式执行此操作,例如,

This This Is Is 
 1     1   2  3

如果它完成了两次,它将继续永远计数。

这是我的代码:

sent = input("Enter your sentence:").lower()
sentlist = sent.split()
print (sent)

for i in sentlist:
    if sentlist.index(i) in newlist:
        newlist.append(sentlist.index(i))
    else:
        newlist.append(int(count))
        count = count + 1
intlist = [x+1 for x in newlist]
print (intlist)

希望有人可以帮助我。

2 个答案:

答案 0 :(得分:0)

您可以使用字典存储每个唯一字以及在输入列表中首次显示它的位置/索引。然后可以使用该词典有效地获取每个单词的位置/索引,然后将其附加到newlist

sentlist = input("Enter your sentence:").lower().split()

newlist = []
position = 0
d = {}

for word in sentlist:
    if word not in d:
        position += 1
        d[word] = position
    newlist.append(d[word])

print(newlist)

<强>输出

输入This is a This is a

[1, 2, 3, 1, 2, 3]

This This Is Is

[1, 1, 2, 2]

Hello this is a This is a bye

[1, 2, 3, 4, 2, 3, 4, 5]

Hello hello hello hello Hello

[1, 1, 1, 1, 1]

答案 1 :(得分:0)

为什么您的解决方案会返回错误的结果

当您遇到一个新单词时(在else-case中),您会在列表中添加一个新数字,但这个数字不是单词的索引,而是列表中已有的单词数。 / p>

第二次输入时将执行的步骤(“This This Is Is”)

  1. i == "this"索引为0且0不在新列表中,因此它将0附加到列表并将count递增到1
  2. i == "this"也有索引0已经在新列表中,所以它再添加一次
  3. i == "is"的索引 2 不在新列表中,因此会将count追加到新列表(其值 1 )并且增加它
  4. i == "is"的索引 2 不在新列表中,因此会将count追加到新列表(其值 2 )和增加它
  5. 要解决此问题,请使用sentlist.index()代替count

    更好的解决方案

    为了改善这种使用字典而不是列表。这允许您有效地存储遇到的单词的位置并构建结果。

    示例:

    sentence = input("Enter your sentence:").lower()
    words = sentence.split()
    
    positions = {}   # positions for each word
    count = 0        # number of unique words
    poslist = []     # the positions for the given sentence
    
    for word in words:
        if word in positions:
            pos = positions[word] # get the position of word from the dictionary
            poslist.append(pos)
        else:
            # new word encountered
            count += 1
            positions[word] = count # store the position for word in the dictionary
            poslist.append(count)
    
    print(poslist)