相关疑难解决方法(0)

为什么元组需要列表理解中的parantheses

众所周知,元组不是用括号定义的,而是用逗号定义的.从文档引用:

元组由许多以逗号分隔的值组成

因此:

myVar1 = 'a', 'b', 'c'
type(myVar1)
# Result:
<type 'tuple'>
Run Code Online (Sandbox Code Playgroud)

另一个惊人的例子是:

myVar2 = ('a')
type(myVar2)
# Result:
<type 'str'>  

myVar3 = ('a',)
type(myVar3)
# Result:
<type 'tuple'>
Run Code Online (Sandbox Code Playgroud)

即使是单元素元组也需要逗号,并且总是使用括号来避免混淆.我的问题是:为什么我们不能在列表推导中省略数组的括号?例如:

myList1 = ['a', 'b']
myList2 = ['c', 'd']

print([(v1,v2) for v1 in myList1 for v2 in myList2])
# Works, result:
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

print([v1,v2 for v1 in myList1 for v2 in myList2])
# Does not work, result:
SyntaxError: invalid syntax …
Run Code Online (Sandbox Code Playgroud)

python tuples list-comprehension python-2.7 python-3.x

6
推荐指数
1
解决办法
218
查看次数