我想遍历一个列表,在列表开头的每个列表的索引[0]中插入一个日期.

基本上,‘here’是我想要的日期所在的位置:

for x in numlist:
    x.insert(0,"Here")
    print(x)
['Here', 16, 22, 25, 37, 40]
['Here', 18, 19, 21, 25, 30]
['Here', 20, 22, 33, 34, 39]

一个列表由字符串组成,另一个列表由列表组成.

for x in daylist:
    print(x)
2022-11-14
2022-11-15
<class 'str'>

for x in numlist:
    print(x)
[10, 17, 21, 30, 31]
[12, 14, 15, 34, 41]
<class 'list'>

我已经能够将列表压缩在一起,但我希望将该日期作为数字的一部分,这样当我迭代列表时,它们就像一个整体.

最后,我可能还想向其中添加其他字段,这样列表中的每个元素都可能由数字、日期和ID号组成.

masterlist = [j for i in zip(daylist,numlist) for j in i]
print(masterlist)
OUTPUT: ['2022-08-07', [16, 22, 25, 37, 40], '2022-08-08', [18, 19, 21, 25, 30], '2022-08-09', [20, 22, 33, 34, 39],

我觉得我已经很接近了,但嵌套的for循环似乎工作得不太好,我只是厌倦了猜测:).我已经有一段时间没用过Python 了.

谢谢.

推荐答案

如果我没有理解错的话,你可以用zipdaylistnumlist压缩在一起,用.insert:

daylist = ["2022-11-14", "2022-11-15"]
numlist = [[10, 17, 21, 30, 31], [12, 14, 15, 34, 41]]

for d, l in zip(daylist, numlist):
    l.insert(0, d)

print(numlist)

打印:

[
 ["2022-11-14", 10, 17, 21, 30, 31], 
 ["2022-11-15", 12, 14, 15, 34, 41]
]

Python-3.x相关问答推荐

Pandas 中每行的最大值范围

只有在Chrome尚未打开的情况下,打开Chrome后,PySimpleGUI窗口才会崩溃

在循环访问XML中的多个层时,xml.etree.Elementree Python3解析器不起作用

如何使用Python将嵌套的XML转换为CSV

切片时是否在NumPy ND数组中创建新对象?

PythonPandas READ_EXCEL空数据帧

如何提高 snowpark 程序的性能?

有没有一种方法可以通过输入从 0 到 255 的 R、G 和 B 值来生成 RGB colored颜色 ,而无需使用 python 中的 matplotlib 模块?

Pandas matplotlib:条形图占总数的百分比

为什么 Sympy 不能解决我的非线性系统? Python 解释器一直在执行,直到我终止进程

Jupyter Notebook 拒绝打印一些字符串

如何将元组列表拆分为两个单独的列表?

为什么 setattr 在绑定方法上失败

获取嵌套字典的所有键

Python 3x 的最佳机器学习包?

Python在OrderedDict中 Select 第i个元素

Python 的 unittest 和 unittest2 模块有什么区别?

0 是 0 == 0(#evaluates 为真?)

为什么排序列表比未排序列表大

Python:如何在 Windows 资源管理器中打开文件夹(Python 3.6.2、Windows 10)