Home > Software design >  Inserting str into index[0] for each list in a list of lists. Python
Inserting str into index[0] for each list in a list of lists. Python

Time:08-08

I would like to iterate through a list of lists inserting a date into each list's index [0] at the beginning of the list.

Basically, 'Here' is where I want the date located:

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]

One list consists of Strings and the other is a list of lists.

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'>

I've been able to zip the lists together, but I would like to have that date as actually part of the numbers so when I iterate through the lists they're as one.

Eventually, I may want to add other fields to it as well so each element in the list consists of the numbers, the date, and an id number too maybe.

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],

I feel like I am fairly close, but nested for loops don't seem to work too well and I am just tired of guessing anymore :). It's been a while since I used python.

Thanks.

CodePudding user response:

If I understand you correctly, you can use zip to zip daylist and numlist together and the use .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)

Prints:

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

CodePudding user response:

Using iterators:

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

print([[next(daylist), *nums] for nums in numlist])

Output:

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