简体   繁体   English

为列表中的每个字符串分配一个数字。 Python 3.6

[英]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.

相关问题 总结列表中的十进制数。 Python - sum the decimal number in list. python 在用户输入列表中查找每个数字的平方。 (Python 3.x) - Finding the squares of each number in a user input list. (Python 3.x) 使用function和random从列表中输出两个新项目。 (Python 3.6) - Using functions and random to output two new items from a list. (Python 3.6) 比较3个列表,如果每个列表中包含字母或值,则回答为true。 Python 3 - Comparing 3 lists answering true if letter or value is in each list. Python 3 列表中的位置。 蟒蛇 - positions in a list. python 将字符串转换为列表。 Python [string.split()表现得很奇怪] - Convert string to list. Python [string.split() acting weird] Python,检查数字是否在列表中的多个范围内。 - Python, check if a number is in a range of many ranges in a list. 如何获取在python列表中生成的随机数的位置? - How to get the position of a random number generated in a python list.? 将 dataframe 中的每个字符串元素与一个列表进行比较,并将其分配给一个列 python pandas - Compare each string element in a dataframe to a list and assign it to a column, python pandas 我想从文件中获取数字并跳过任何字符串,之后我想将每个数字附加到一个列表中。 在蟒蛇 - I want to take numbers from a file and skip any string, after that i want to append every number inside one list. in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM