简体   繁体   中英

Insert element at every nth location in list of lists

I'm working on a project in Python and came across a problem. I have a long data set that is a list of two ply lists that looks like this:

[('A', 15), ('C', 125), ('L', 37), ('J', 215), ('M', 829), etc.]

What I want to do is insert another data set that has the same first element but a different second like this:

[('A', 2), ('C', 4), ('L', 9), ('J', 7), ('M', 15), etc.]

so that the first set of data has three elements to each list, like this:

[('A', 15, 2), ('C', 125, 4), ('L', 37, 9), ('J', 215, 7), ('M', 829, 15), etc.]

What kind of code would I need to set up to get this third set of data to add its second element to my first set of data?

If this is by position and the lists have equal length, you can try this:

l1 = [('A', 15), ('C', 125), ('L', 37), ('J', 215), ('M', 829)]
l2 = [('A', 2), ('C', 4), ('L', 9), ('J', 7), ('M', 15)]

l_combined = [(i[0][0], i[0][1], i[1][1]) for i in zip(l1, l2)]

What you basically do is to combine both lists into a larger tuple, where you then access each element by position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM