需要有关python代码中突出显示行的帮助:
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split() <--- doubt
scores = list(map(float, line)) <--- doubt
student_marks[name] = scores
print (student_marks)
我得到的输出如下:
2
abc 23 34 45
def 45 46 47
{'abc': [23.0, 34.0, 45.0], 'def': [45.0, 46.0, 47.0]}
你们能帮我解释一下代码中标记行的必要性吗?无法完全理解这个概念。
答案 0 :(得分:1)
name, *line = input().split() <--- doubt
input() # reads single line of input
# 'abc 23 34 45'
.split() # splits it into a list of whitespace separated tokens
# ['abc', '23', '34', '45']
name, *line = ... # name is assigned first token, line a list of the remaining tokens
name # 'abc'
line # ['23', '34', '45']
scores = list(map(float, line)) # maps float function onto the list of strings
scores # [23.0, 34.0, 45.0]
一些参考文献:
答案 1 :(得分:1)
1)name, *line = input().split() <--- 疑问
* 用于存储来自 split 语句的额外返回。 假设您有:
name, *line = input().split()
打印(名称)
打印(*行)
然后你运行这段代码并说你输入了:“abc 23 34 45”,它会打印出来:
ABC
[23, 34, 45]
2)scores = list(map(float, line)) <--- 怀疑
这里,map() 函数在将给定函数应用于给定可迭代对象(列表、元组等)的每个项目后返回结果的映射对象(它是一个迭代器)。 更多理解请参考:https://www.geeksforgeeks.org/python-map-function/
->map() 函数将浮点函数映射到字符串列表上。
例如: 行 = [23, 34, 45] 然后scores = list(map(float, line)) 将输出到:scores = [23.0, 34.0, 45.0]
答案 2 :(得分:0)
第name, *line = input().split()
行用空格分隔输入,将第一个项目分配给name
,其余项目作为列表分配给line
,在列表中下一行scores = list(map(float, line))
被映射到scores
中的浮点数列表。
答案 3 :(得分:0)
name, *line = "foo 23 34 45".split()
assert(name == "foo");
assert(line == ["23", "34", "45"])
https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
scores = list(map(float, line))
assert(scores == [23.0, 34.0, 45.0])
答案 4 :(得分:0)
您想从我们使用的用户那里获取数据
scanf('%d %d', %name, %value)
name, value=input(), input()
另一种解决方案是:
name, value=input().split()
使用拆分方法