在下面的代码中,我试图解压缩一个 zip 对象。
x = [1, 2, 3]; y = ['a', 'b', 'c']
z = zip(x, y)
#print(list(z)) #2nd print statement returns [] if this line is uncommented
unzip = zip(*z)
print(list(unzip)) #returns [(1, 2, 3), ('a', 'b', 'c')]
Run Code Online (Sandbox Code Playgroud)
如果我保持代码不变,它就可以正常工作。但是在取消注释第一个打印语句时,第二个打印语句返回一个空列表而不是返回解压缩的列表对象。为什么?
为什么这段代码运行良好并且不抛出异常?
def myzip(*args):
iters = [iter(arg) for arg in args]
try:
while True:
yield tuple([next(it) for it in iters])
except StopIteration:
return
for x, y, z in myzip([1, 2], [3, 4], [5, 6]):
print(x, y, z)
Run Code Online (Sandbox Code Playgroud)
但如果这条线
yield tuple([next(it) for it in iters])
Run Code Online (Sandbox Code Playgroud)
替换为
yield tuple(next(it) for it in iters)
Run Code Online (Sandbox Code Playgroud)
然后一切都停止工作并抛出RuntimeError?
我有一个包含元素列表的列表(每个内部列表中的元素数量不相同),我想将同一索引中的所有元素分组到单独的组中并返回每个组中的最大值:例如,
elements = [[89, 213, 317], [106, 191, 314], [87]]
Run Code Online (Sandbox Code Playgroud)
我想像这样对这些元素进行分组,
groups = [[89,106,87],[213,191],[317,314]]
Run Code Online (Sandbox Code Playgroud)
预期结果是组中每个列表的最大值:106,213 和 317
我尝试使用以下代码对元素进行分组:
w = zip(*elements)
result_list = list(w)
print(result_list)
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
[(89, 106, 87)]
Run Code Online (Sandbox Code Playgroud) 代码:
boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
for i, boylist in enumerate(boylist):
print(f'Index {i} is {boylist} in my list')
#boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
for boylist, girllist in zip(boylist, girllist):
print(f'{boylist} and {girllist} form a nice couple')\
Run Code Online (Sandbox Code Playgroud)
输出:
Index 0 is Jim in my list
Index 1 is James in my list
Index 2 is Jack in my list
Index 3 is John in my list
Index 4 is Jason …Run Code Online (Sandbox Code Playgroud) 我正在做一个简单的列表理解:以替代顺序组合两个列表并制作另一个列表。
big_list = [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
Run Code Online (Sandbox Code Playgroud)
预期输出:
['2022-01-01','2022-01-31','2022-02-01','2022-02-28']
Run Code Online (Sandbox Code Playgroud)
当前输出:
Cell In[35], line 1
[i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
^
SyntaxError: did you forget parentheses around the comprehension target?
Run Code Online (Sandbox Code Playgroud)