【问题标题】:How can I assign each item in a list a seperate number, and then print these numbers as a string? - Python [closed]如何为列表中的每个项目分配一个单独的数字,然后将这些数字打印为字符串? - Python [关闭]
【发布时间】:2016-09-21 16:17:45
【问题描述】:

请多多包涵,因为我对 python 还很陌生。

我想取一个由几个单词组成的字符串,将其更改为一个列表,并给列表中的每个项目一个单独的数字(我猜你称之为索引)。我环顾四周寻找解决方案,并看到经常提到的枚举函数。我可以使用它,但我想做的是为字符串中的重复单词分配与它之前的索引相同的索引。我不知道如何做到这一点!

例如,如果示例输入输出字符串是:

"How does one do this How does one do this"

示例输出字符串应为:

"1234512345" 

解释:单词“How”被赋值为1,“does”被赋值为2等等。

感谢任何帮助!

【问题讨论】:

  • 嘿看,你开始学习如何编码了!伟大的。接受您告诉我们的内容,使用# 将其放入注释块中,然后开始编写您告诉我们的内容。你想要一些东西,你会怎么做。
  • Stack Overflow 不是代码编写或教程服务。请edit您的问题并发布您迄今为止尝试过的内容,包括示例输入、预期输出、实际输出(如果有)以及任何错误或回溯的全文
  • 对不起,我会记住这个以备将来使用!

标签: python string list enumerate


【解决方案1】:

以下是示例代码。每个变量的值都在每个步骤的注释中提到,以向您解释它是如何工作的:

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 持有我上面示例中的值。

【讨论】:

  • 谢谢你,这很好用!
【解决方案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

【讨论】:

  • 非常感谢,辛苦了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多