Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Input_Append - Fatal编程技术网

Python 将输出转换为列表

Python 将输出转换为列表,python,list,input,append,Python,List,Input,Append,这是我的密码 userinput = input("Enter a sentence: ") wordlist = userinput.split() uniquelist = [] for word in wordlist: if word not in uniquelist: uniquelist.append(word) print ("Here are the words in their first appearing index form: ")

这是我的密码

 userinput = input("Enter a sentence: ")
 wordlist = userinput.split()
 uniquelist = []
 for word in wordlist:
     if word not in uniquelist:
         uniquelist.append(word)
 print ("Here are the words in their first appearing index form: ")
 my_indexes = ' '.join(str(uniquelist.index(word)+1) for word in wordlist)
 print (uniquelist)
 print (my_indexes)
它要求用户输入一个没有标点符号的句子,然后程序返回该句子中每个单词的位置。如果任何单词出现不止一次,它将输出第一次出现的索引位置

例如:如果输入是-我喜欢编码,因为编码很有趣 . 输出为-

1234567

我想它是一个字符串,我该如何转换输出?我不确定,因此有一个模糊的标题-一个有格式的列表

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


在当前代码中,使用生成器表达式,然后加入值,以获得以下位置的当前输出字符串:

my_indexes = ' '.join(str(uniquelist.index(word)+1) for word in wordlist)  
相反,如果您还需要中间列表,则可以使用列表理解来打断此行,如下所示:

您首先不应该使用ìndex,因为它处于启用状态,这将影响大型单词列表的性能。更好的方法包括使用创建从单词到其唯一索引的映射,然后使用该映射构建唯一索引列表:

> wordlist = userinput.split()
> id_s = {c: i for i, c in enumerate(set(wordlist), start=1)}
> id_s
{'code': 0, 'like': 1, 'I': 2, 'is': 3, 'to': 4, 'because': 5, 'fun': 6}
> [id_s[c] for c in list]  
[1, 6, 7, 3, 2, 7, 3, 5, 4]

这个问题已经得到了回答,是来自家庭作业评估吗?为什么同一个奇怪的问题在同一周内被贴了两次?如果有人能投票给我这个问题的正确答案,那么我就可以结束这个问题duplicate@hansaplast谢谢,不是家庭作业,而是20周评估的一部分,我想我最好现在就做,然后再节省时间复习,而不是在以后的考试时间完成作业:-@hansaplast我会删除它。我删除了你代码答案的第一部分,然后用接下来的3行代码替换它。但是当我打印我的索引时,我得到了相同的结果!不可以。在这种情况下,您必须打印索引列表。因为这正是你所需要的价值。谢谢,额外的解释很有帮助。对不起,我一点都不懂,我只是一个学生-初学者,在pythonI中添加了一些解释和文档链接。
> wordlist = userinput.split()
> id_s = {c: i for i, c in enumerate(set(wordlist), start=1)}
> id_s
{'code': 0, 'like': 1, 'I': 2, 'is': 3, 'to': 4, 'because': 5, 'fun': 6}
> [id_s[c] for c in list]  
[1, 6, 7, 3, 2, 7, 3, 5, 4]