如何为列表中的每个项目分配一个单独的数字,然后将这些数字打印为字符串? - Python
How can I assign each item in a list a seperate number, and then print these numbers as a string? - Python
请多多包涵,因为我是 python 的新手。
我想取一个由几个单词组成的字符串,将其更改为一个列表,并为列表中的每个项目指定一个单独的编号(我猜你称之为索引)。我四处寻找解决方案并看到经常提到的枚举函数。我可以使用它,但我想做的是为字符串中的重复词分配与之前的相同的索引。我不知道如何完成这个!
例如,如果示例输入输出字符串是:
"How does one do this How does one do this"
示例输出字符串应为:
"1234512345"
解释:单词"How"赋值1,"does"赋值2等
感谢任何帮助!
标记字符串,然后在每次发现新词时关联一个数字。
string1 = 'How does one do this How does one do this'
tokens = string1.split()
d = {}
count=1
rval=[]
for t in tokens:
if t in d:
# token has a reference in dictionary, append it to the list, as string
rval.append(str(d[t]))
else:
# create a new reference and append it to the list
d[t] = count
rval.append(str(count))
count+=1
print("".join(rval))
结果
1234512345
下面是示例代码。每个变量的值都在每个步骤的评论中提到,以向您解释它是如何工作的:
my_string = "How does one do this How does one do this"
my_list = my_string.split(" ")
# my_list: ['How', 'does', 'one', 'do', 'this', 'How', 'does', 'one', 'do', 'this']
count = 1
my_dict = {}
for item in my_list:
if item not in my_dict:
my_dict[item] = count
count += 1
# my_dict: {'this': 5, 'How': 1, 'does': 2, 'do': 4, 'one': 3}
num_list = [str(my_dict[item]) for item in my_list]
# num_list: ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5']
num_string = ''.join(num_list)
# num_string: '1234512345'
或者,如果您需要一行解决方案,您可以使用list.index()
来实现它。下面是等效代码:
num_string = ''.join([str(my_list.index(item)+1) for item in my_list])
# num_string: '1234512345'
其中 my_list
保存我上面示例中的值。
请多多包涵,因为我是 python 的新手。
我想取一个由几个单词组成的字符串,将其更改为一个列表,并为列表中的每个项目指定一个单独的编号(我猜你称之为索引)。我四处寻找解决方案并看到经常提到的枚举函数。我可以使用它,但我想做的是为字符串中的重复词分配与之前的相同的索引。我不知道如何完成这个!
例如,如果示例输入输出字符串是:
"How does one do this How does one do this"
示例输出字符串应为:
"1234512345"
解释:单词"How"赋值1,"does"赋值2等
感谢任何帮助!
标记字符串,然后在每次发现新词时关联一个数字。
string1 = 'How does one do this How does one do this'
tokens = string1.split()
d = {}
count=1
rval=[]
for t in tokens:
if t in d:
# token has a reference in dictionary, append it to the list, as string
rval.append(str(d[t]))
else:
# create a new reference and append it to the list
d[t] = count
rval.append(str(count))
count+=1
print("".join(rval))
结果
1234512345
下面是示例代码。每个变量的值都在每个步骤的评论中提到,以向您解释它是如何工作的:
my_string = "How does one do this How does one do this"
my_list = my_string.split(" ")
# my_list: ['How', 'does', 'one', 'do', 'this', 'How', 'does', 'one', 'do', 'this']
count = 1
my_dict = {}
for item in my_list:
if item not in my_dict:
my_dict[item] = count
count += 1
# my_dict: {'this': 5, 'How': 1, 'does': 2, 'do': 4, 'one': 3}
num_list = [str(my_dict[item]) for item in my_list]
# num_list: ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5']
num_string = ''.join(num_list)
# num_string: '1234512345'
或者,如果您需要一行解决方案,您可以使用list.index()
来实现它。下面是等效代码:
num_string = ''.join([str(my_list.index(item)+1) for item in my_list])
# num_string: '1234512345'
其中 my_list
保存我上面示例中的值。