python - python从多个列表中旋转选择
问题描述
我有 4 个列表如下:
import numpy as np
file1 = np.arange(0, 4).tolist()
file2 = np.arange(3, 7).tolist()
file3 = np.arange(7, 11).tolist()
file4 = np.arange(11, 15).tolist()
我想从每个列表中轮流选择,最终得到如下一组:
final = {0, 4, 9, 14}
我有一个可行的解决方案,但我想知道是否有更简单的方法或更pythonic的方法来做到这一点?
def get_rotated(file1: list,
file2: list,
file3: list,
file4: list):
count = 0
i = 0
final = set()
while i < (get_len(file1) -1):
print('here')
if count == 0:
print(i)
tag = file1[i]
count+=1
final.add(tag)
i += 1
if count == 1:
print(i)
tag = file2[i]
count+=1
final.add(tag)
i += 1
if count == 2:
print(i)
tag = file3[i]
count+=1
final.add(tag)
i += 1
if count == 3:
print(i)
tag = file4[i]
count=0
final.add(tag)
i += 1
return final
这将返回正确的集合 {0, 4, 9, 14}。如果列表大小更大,我希望这可以继续分组旋转选择。
解决方案
这就是你需要的。您应该通过迭代使用如下列表名称
import numpy as np
file1 = np.arange(0, 4).tolist()
file2 = np.arange(3, 7).tolist()
file3 = np.arange(7, 11).tolist()
file4 = np.arange(11, 15).tolist()
countOfLists = 4
finalList = []
for i in range(1, countOfLists + 1):
finalList.append(globals()['file%s'%i][i - 1])
print(finalList)
推荐阅读
- java - Jackson 与 ParameterNamesModule 未能反序列化类
- android - 无论布局类型如何,如何在屏幕中心显示 ProgressBar
- android - 如何从 Kotlin DSL build.gradle 中的所有依赖项中排除库?
- odoo - 如何修复网站销售模块中 [/shop/checkout] 和 [/payment] 之间的 ODOO 9 送货地址不匹配?
- python - 安装 Jupyter Hub 后,Conda 不再工作
- mysql - 春季启动MongoDB配置
- css - 改变 Angular 材料微调器的直径会破坏它
- r - r 中每日数据的 stl 分解显示错误只允许单变量系列
- python-3.x - 根据列的实际值从对象转换熊猫数据框列类型
- python - 如何将全局变量分配到另一个文件中