Python列表理解:获取引用代替值

时间:2018-03-19 23:33:47

标签: list pointers reference list-comprehension

我正在尝试获取x_trainx_test的引用,以便此代码中的*ref

x_train = [ None for _ in range(len(x))]
x_test = [ None for _ in range(len(x))]

# criss-cross merge list / zip merge
recv = [item for sublist in zip(x_train, x_test) for item in sublist]
# If x_train was [10,11,12] and x_test was [13,14,15], recv will have [10,13,11,14,12,15]
# But unfortunately the above line gives only the values and not references

*recv, y_train, y_test = train_test_split(*x, y, test_size=0.2, random_state=np.random, shuffle=True)
# values received at *recv to be assigned to x_train[0], x_test[0], x_train[1], x_test[1], ...

将直接将收到的值分配给x_trainx_test,以通过使用引用代替列表值来解决second part of my answer here

如何获取列表元素的引用或指针?

编辑:我知道python在内部使用指针,但有没有办法为列表理解做到这一点?

作业操作:

print('Reference Assignment')
a = [1,2,3]
b = a
b.append(4)
print('a',a)
print('b',b)

输出:

Reference Assignment
a [1, 2, 3, 4]
b [1, 2, 3, 4]

列表理解:

print('List Comprehension')
a = [1,2,3]
b = [item for item in a]
b.append(4)
print('a',a)
print('b',b)

输出:

List Comprehension
a [1, 2, 3]
b [1, 2, 3, 4]

游乐场here

0 个答案:

没有答案