[英]Assign a number to each string in a list. Python 3.6
I am trying to to write a code that takes input, splits it into a list, and then assigns a number to each string in the list. 我正在尝试编写一个接受输入的代码,将其拆分为一个列表,然后为列表中的每个字符串分配一个数字。
For example: If my input was "hello hello goodbye hello" Then it would output "1121". 例如:如果我的输入是“ hello hello再见hello”,那么它将输出“ 1121”。
This is the code I have written so far: 这是我到目前为止编写的代码:
sentence = input("What is your sentence? ").lower()
list_s = str.split(sentence)
for i in range(len(list_s)):
Use a dictionary containing the strings as keys and the number as value: 使用包含字符串作为键和数字作为值的字典:
inp = 'hello hello world hello'
d = {}
idx = 1
for word in inp.lower().split():
# If the word is in the dictionary print the corresponding number
if word in d:
print(d[word], end='')
# Otherwise print the next number and add the number to the dictionary
else:
print(idx, end='')
d[word] = idx
idx += 1
I proposed the dictionary because the in
operation is very fast and one needs to store 2 things: The string and the value. 我之所以提出字典,是因为
in
操作非常快,并且其中一个需要存储2种东西:字符串和值。 Making the dictionary a very suitable data structure for that problem. 使字典成为解决该问题的非常合适的数据结构。
If you like it shorter you could use a list comprehension (using the len(d)+1
"trick" from trincots answer): 如果您更喜欢它,可以使用列表推导(使用从小支票答案中的
len(d)+1
“ trick”):
inp = 'hello hello world hello'
d = {}
result = [d.setdefault(word, len(d)+1) for word in inp.lower().split()]
Where result
would be a list containing [1, 1, 2, 1]
which you could print using: result
将是包含[1, 1, 2, 1]
,您可以使用以下命令进行打印:
print(''.join(map(str, result)))
Or (thanks Stefan Pochmann for the hint): 或者(感谢Stefan Pochmann的提示):
print(*result, sep="")
As MSeifert, I would suggest a dictionary. 作为MSeifert,我建议使用字典。 You can produce the assigned number from the size of the dictionary at the moment a new word is added.
您可以在添加新单词时根据字典的大小生成分配的数字。 The final result can be produced as a list with list comprehension:
最终结果可以生成为具有列表理解的列表:
list_s = str.split("hello hello goodbye hello")
d = {} # a dictionary, which will store for each word a number
for word in list_s:
if not word in d: # first time we see this word?
d[word] = len(d)+1 # assign to this word a unique number
result = [d[word] for word in list_s] # translate each word to its unique number
print (result) # [1, 1, 2, 1]
You can use a set
: 您可以使用一
set
:
def get_numbers(s):
s = s.split()
new_s = [a for i, a in enumerate(s) if a not in s[:i]]
return [new_s.index(i)+1 for i in s]
l = ["hello hello goodbye hello", "hello goodbye hello hello"]
final_l = list(map(get_numbers, l))
Output: 输出:
[[1, 1, 2, 1], [1, 2, 1, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.