这是我的代码,
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)
它询问用户输入,没有标点符号的句子,程序返回该句子中每个单词的位置。如果任何单词出现多次,则输出第一次出现的索引位置。
例如:如果输入是 - “我喜欢编码因为代码很有趣” 。输出将是 -
1 2 3 4 5 3 4 6 7
我如何转换输出,我猜它是一个字符串?我不确定因此模糊的标题 - 具有格式
的列表[1,2,3,4,5,3,4,6,7]
答案 0 :(得分:1)
您不应该首先使用[{u'base_url': u'/',
u'hostname': u'localhost',
u'notebook_dir': u'/Users/username/your/notebook/path',
u'pid':123,
u'port': 8888,
u'secure': False,
u'url': u'http://localhost:8888/'},
...
{u'base_url': u'/',
u'hostname': u'localhost',
u'notebook_dir': u'/Users/username/your/other/notebook/path',
u'pid': 1234,
u'port': 8889,
u'secure': True,
u'url': u'http://localhost:8889/'}]
,因为它是ìndex
,这会损害大型单词列表的性能。更好的方法包括使用enumerate从单词到其唯一索引创建dict
,然后使用该映射构建唯一索引的O(N)
:
list
答案 1 :(得分:0)
在您当前的代码中,您正在使用生成器表达式,然后您将加入值以获取当前输出字符串:
my_indexes = ' '.join(str(uniquelist.index(word)+1) for word in wordlist)
相反,如果你还想要中间列表,那么你可以使用 list comprehension 来打破这一行:
# As you mentioned in output, you need list of integer indexes
index_list = [uniquelist.index(word)+1 for word in wordlist] # list of indexes
str_index_list = list(map(str, index_list)) # convert list of `int` index as `str` index
# If you want list of `str` indexes. You may replace the above two line
# via using generator expression in your code as list comprehension as:
# index_list = [str(uniquelist.index(word)+1) for word in wordlist]
my_indexes = ' '.join(str_index_list) # value of `str` in your current code