Python 在这个例子中加号是做什么的?
考虑到这两个变量:Python 在这个例子中加号是做什么的?,python,python-3.x,Python,Python 3.x,考虑到这两个变量: Row = [Row(name='a', age=12, gender='man', score='123'), Row(name='b', age=23, gender='woman', score='110'), Row(name='c', age=120, gender='man', score='60')] 及 当我循环遍历它们以获得每行中带有加号的最大项时,我得到以下结果: for i in range(4): print(max([str(x[i])
Row = [Row(name='a', age=12, gender='man', score='123'), Row(name='b', age=23, gender='woman', score='110'), Row(name='c', age=120, gender='man', score='60')]
及
当我循环遍历它们以获得每行中带有加号的最大项时,我得到以下结果:
for i in range(4):
print(max([str(x[i]) for x in Row]+[headers[i]]))
...
name
age
woman
score
for i in range(4):
print(max([str(x[i]) for x in Row],[headers[i]]))
...
['name']
['age']
['man', 'woman', 'man']
['score']
但是,当我用逗号替换加号时,我得到以下结果:
for i in range(4):
print(max([str(x[i]) for x in Row]+[headers[i]]))
...
name
age
woman
score
for i in range(4):
print(max([str(x[i]) for x in Row],[headers[i]]))
...
['name']
['age']
['man', 'woman', 'man']
['score']
所以,基本上我的问题是,加号是做什么的?通常我会用逗号来调用max函数,比如说
max(list1,list2)
,但在本例中max
函数的调用方式是这样的max(list1+list2)
它连接列表,也就是说它将两个列表连接到一个大列表中:
>>> a = [1, 2, 3]
>>> b = ['x', 'y', 'z']
>>> c = a+b
>>> print(c)
[1, 2, 3, 'x', 'y', 'z']
如果您有一个print
语句,后面跟有逗号分隔的项目,那么它将只打印这些项目,并用空格分隔
>>> print(a,b)
[1, 2, 3] ['x', 'y', 'z']
当您调用max(list1,list2)
时,这意味着,“查看两项,list1
和list2
,并返回具有“最大”值的项。”当您调用max(list1+list2)
时,这意味着,“将list1
和list2
组合到一个大列表中,然后从组合列表中选择“最大”项。”我在这里用引号括起“最大”一词,因为max()
也适用于非数字项
>>> d = [7, 8, 9]
>>> e = [0, 75, 21]
>>> print(max(d,e))
[7, 8, 9]
>>> print(max(d+e))
75
第一个列表返回[7,8,9]
的原因是Python认为它比[0,75,21]
要“大”。这是因为在比较两个列表时,Python会从词汇角度对其进行检查。7大于0,因此:
>>> d > e
True
它连接列表,也就是说它将两个列表连接到一个大列表中:
>>> a = [1, 2, 3]
>>> b = ['x', 'y', 'z']
>>> c = a+b
>>> print(c)
[1, 2, 3, 'x', 'y', 'z']
如果您有一个print
语句,后面跟有逗号分隔的项目,那么它将只打印这些项目,并用空格分隔
>>> print(a,b)
[1, 2, 3] ['x', 'y', 'z']
当您调用max(list1,list2)
时,这意味着,“查看两个项目,list1
和list2
,并返回具有“最大”值的项目。”当您调用max(list1+list2)
时,这意味着,“将list1
和list2
组合成一个大列表,然后从组合列表中选择“最大”项。“我在这里用引号括起“最大”一词,因为max()
也适用于非数字项
>>> d = [7, 8, 9]
>>> e = [0, 75, 21]
>>> print(max(d,e))
[7, 8, 9]
>>> print(max(d+e))
75
第一个列表返回[7,8,9]
的原因是Python认为它比[0,75,21]
要“大”。这是因为在比较两个列表时,Python会从词汇角度对其进行检查。7大于0,因此:
>>> d > e
True
它将列表添加到一起
e、 g
输出:
它将列表添加到一起
e、 g
输出:
它将两个列表合并为一个大列表
# The two different lists
letters = ['a','b','c']
numbers = [1,2,3]
# The plus sign
print(letter + number)
# Your result
['a','b','c',1,2,3]
它将两个列表合并为一个大列表
# The two different lists
letters = ['a','b','c']
numbers = [1,2,3]
# The plus sign
print(letter + number)
# Your result
['a','b','c',1,2,3]
它连接了listsI可能会假设一个干净的重复,但它们似乎都与
append
/extend
相比较,而这并不是OP真正想要的:/在第一个示例中,[str(x[i])表示行中的x+[headers[i]
得到一个由两个字符串组成的数组,因此max(['a',b'])返回字符串。在第二个示例中:max(['a'],['b'])这将返回数组。不要使用同一个变量行
来保存列表作为类的名称。这将有效地取消对类的定义。它将列表串联起来。我可能会认为这是一个干净的重复,但它们似乎都与追加
/扩展
相比较,而这并不是OP真正想要的:/在第一个示例中[str(x[i])对于行中的x]+[headers[i]
得到一个由两个字符串组成的数组,因此max(['a',b'])返回字符串。在第二个示例中:max(['a'],['b'])返回数组。不要使用相同的变量行
来保存列表作为类的名称。这会有效地取消类的定义。