我很难理解我学习的这段代码。 “正常”循环中的代码如何?
1:
a, b = zip(*[(X, X_type) for X_list, X_type in zip(df['X_seq'], df['type']) for X in X_list])
和2:
for j in range(0,2):
X_seq += zip(*(X_list[i:] for i in range(3)))
我自己尝试过,但总是出现错误或其他结果。还有这个zip函数使它更加复杂...
谢谢你
答案 0 :(得分:4)
第一个示例:
a, b = zip(*[ # 5
(X, X_type) # 4
for X_list, X_type in zip( # 2
df['X_seq'], df['type']) # 1
for X in X_list # 3
])
是
的缩写tups = []
# 1 - iterate over the length of the dataframe columns
# (should be the same for X_seq and type)
for i in range(len(df['X_seq'])):
# 2 - Take the corresponding values from X_seq and type,
# and put them in variables named X_list and X_type, respectively
X_list = df['X_seq'][i]
X_type = df['type'][i]
# 3 - Iterate over X_list
for X in X_list:
# 4 - for each X, make a 2-tuple of (X, X_type).
# This will result in duplicating X_type for as many
# values of X as there are in X_list.
tups.append((X, X_type))
# 5 - `zip(*2diterable)` is a trick that essentially flips
# the given iterable - if it was (N x 2), then it's now (2 x N)
# See also a tutorial on the 'unpacking operator', as it's called:
# https://www.geeksforgeeks.org/packing-and-unpacking-arguments-in-python/
# To do this manually:
a, b = [], []
for row in tups:
a.append(row[0])
b.append(row[1])
第二个示例:
for j in range(0,2): # 1
X_seq += # 4
zip(*( # 3
X_list[i:] for i in range(3) # 2
))
是
的缩写# assume X_seq exists already and is a list
# 1 - same for loop as in your given example
for j in range(0, 2):
# 2 - list comprehension over range(3). For each index, take a
# sublist of X_list consisting of every element whose index
# is equal or greater.
seg = []
for i in range(3): # iterates over [0, 1, 2]
seg.append(X_list[i:])
# 3 - unpacking operator again. zip() groups corresponding
# elements, but is limited by the shortest list it's given
zipped = []
for i in range(len(seg[2]): # seg[2] will be the shortest
zipped.append(
(seg[0][i], seg[1][i], seg[2][i])
)
# 4 - list concatenation. Append each tuple in zipped to X_seq
for tup in zipped:
X_seq.append(tup)
这是我能做的最好的事情。对于此代码要完成的工作,我没有任何背景,如果您复制/粘贴其中的任何内容,则应该立即开始工作。但这也许会使您更容易调试代码过程中的任何错误。