[英]How to split a single line input string having Name(1 or more words) and Number into ["Name" , "Number"] in Python?
我是新手。 我在电话簿问题中的一个测试用例失败了。 根据问题,用户应该输入一个单行输入,其中包含一个名称(可以是一个或多个单词),后跟一个数字。 我必须将输入拆分为 ["name","number"] 并将其存储在字典中。 请注意,名称将包含一个或多个单词(例如:John Conor Jr. 或 Apollo Creed)。 我对拆分部分感到困惑。 我尝试了 split() function 和 re.split()。 不确定我能解决这个问题。
样本输入 1:大卫詹姆斯 93930000
示例输入 2:hshhs kskssk sshs 99383000
Output:num = {“大卫詹姆斯”:“93930000”,“hshhs kskssk sshs”:“99383000”}
我需要将它存储在字典中,其中键:值是“大卫詹姆斯”:“93930000”
请帮忙。 谢谢
=====>我找到了解决方案<==========
if __name__ == '__main__':
N=int(input())
phonebook={}
(*name,num) = input().split()
name = ''.join(map(str,name)
phonebook.update({name:num})
print(phonebook)
astrik 方法的话。 但是对于大型数据集,这可能会减慢我的速度。 没有把握。
如果这是您正在寻找的,请检查更新的答案。
# Sample text in a line...
# With a name surname and number
txt = "Tamer Jar 9000"
# We define a dictionary variable
name_dictionary = {}
# We make a list inorder to appened the name and surname to the list
name_with_surname = []
# We split the text and if we print it out it should look something like this
# "Tamer", "Jar", "9000"
# But you need the name and surname together so we do that below
x = txt.split()
# We take the first value of the split text which is "Tamer"
# And we take the second value of the split text us "Jar"
name = x[0]
surname = x[1]
# And here we append them to our list
name_with_surname.append(name + " " + surname)
#print(name_with_surname)
# Finally here to display the values in a dictionary format
# We take the value of the list which is "Tamer Jar" and the value of the number "9000"
name_dictionary[name_with_surname[0]] = x[2]
print(name_dictionary)
如果数据在一行中有太多名称部分,则上述答案无法处理。 在下面试试我的代码。 您可以遍历任何您想要的输入总数。
phonebook = {}
total_inputs = int(input())
for i in range(total_inputs):
name_marks = input().split() # taking input and splitting them by spaces
name = " ".join(x for x in name_marks[:-1]) # extracting the name
marks = name_marks[-1] # extracting the marks
phonebook[name] = marks # storing the marks in the dictionary
这样您就可以存储名称的标记。 它甚至可以处理一个包含许多名称部分的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.