gpt4 book ai didi

python - 如何创建使用其他两个列表的索引和项目创建的列表?

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:45 24 4
gpt4 key购买 nike

我有两个列表。一种是由句子中的位置组成,另一种是由组成句子的单词组成。我想使用 poslist 和 wordlist 重新创建可变句子。

recreate = []
sentence = "This and that, and this and this."
poslist = [1, 2, 3, 2, 4, 2, 5]
wordlist = ['This', 'and', 'that', 'this', 'this.']

我想使用 for 循环来遍历 poslist,如果 poslist 中的项目等于 wordlist 中单词的位置,则会将其附加到新列表中,从而重新创建原始列表。我的第一次尝试是:

for index in poslist:
recreate.append(wordlist[index])
print (recreate)

我必须创建列表字符串才能将列表写入文本文件。当我尝试再次拆分它们并使用上面显示的代码时,它不起作用。它说索引必须是切片或整数或不在列表中的切片。我想要解决这个问题。谢谢。

单词列表是通过以下方式获取的:

sentence = input("Enter a sentence >>") #asking the user for an input
sentence_lower = sentence.lower() #making the sentence lower case
wordlist = [] #creating a empty list
sentencelist = sentence.split() #making the sentence into a list

for word in sentencelist: #for loop iterating over the sentence as a list
if word not in wordlist:
wordlist.append(word)

txtfile = open ("part1.txt", "wt")
for word in wordlist:
txtfile.write(word +"\n")
txtfile.close()

txtfile = open ("part1.txt", "rt")
for item in txtfile:
print (item)
txtfile.close()
print (wordlist)

位置是通过以下方式获取的:

poslist = []

textfile = open ("part2.txt", "wt")
for word in sentencelist:
poslist.append([position + 1 for position, i in enumerate(wordlist) if i == word])

print (poslist)
str1 = " ".join(str(x) for x in poslist)

textfile = open ("part2.txt", "wt")
textfile.write (str1)
textfile.close()

最佳答案

列表是 0 索引的(第一个项目的索引为 0,第二个项目的索引为 1,...),因此如果您想在 中使用“人类”索引,则必须从索引中减去 1 >poslist:

for index in poslist:
recreate.append(wordlist[index-1])
print (recreate)

之后,您可以再次将它们粘合在一起并将它们写入文件:

with open("thefile.txt", "w") as f:
f.write("".join(recreate))

关于python - 如何创建使用其他两个列表的索引和项目创建的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com