Home > Software design >  Split list of lists at nth element
Split list of lists at nth element

Time:10-06

I have a list looking like the one below and I want to return the first nth lists inside of that list. So for example, if n =6 it should return the first 6 lists inside the bigger list.

[[[['Groningen',
    'GM0014',
    231299,
    0.49691957163671263,
    0.5030804283632874,
    0.1246092719812883,
    0.2176490170731391,
    0.2934988910457892,
    0.22006147886501887,
    0.14418134103476452,
    0.6526227956022291,
    0.2415531411722489,
    0.07018620919243057,
    0.035637854033091367],
   ['Amsterdam',
    'GM0363',
    862965,
    0.4957176710527078,
    0.5042823289472922,
    0.14554703840827843,
    0.1257142526058415,
    0.36046421349649177,
    0.24314775222633594,
    0.12512674326305237,
    0.6432080095948272,
    0.2436031588766636,
    0.08585516214446703,
    0.027333669384042227],
   ['Utrecht',
    'GM0344',
    352866,
    0.48986584142422335,
    0.5101341585757766,
    0.17020908786904945,
    0.1524119637482784,
    0.36236701750806255,
    0.21132667924934678,
    0.10368525162526285,
    0.6469027902943327,
    0.26626538119286075,
    0.05933697210839242,
    0.02749485640441414],
   ['Nijmegen',
    'GM0268',
    176731,
    0.4842500749726986,
    0.5157499250273013,
    0.1371293095155915,
    0.1775127170671812,
    0.2857506606084954,
    0.24216464570448873,
    0.15744266710424318,
    0.6046251082153102,
    0.2767256451895819,
    0.08034809965427683,
    0.038301146940830984],

CodePudding user response:

First six elements of a list can be got by slicing:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

my_list[:6] == [1, 2, 3, 4, 5, 6]

To get an inner list, index or iterate over the outer list:

my_nested_list = [
    [ 1,  2,  3,  4,  5,  6,  7,  8],
    [11, 22, 33, 44, 55, 66, 77, 88],
]

# first 6 of first list
my_nested_list[0][:6] == [1, 2, 3, 4, 5, 6]

# first 6 of every list
for inner_list in my_nested_list:
    print(inner_list[:6]) # or yield, append, call some other function…

# or as a list comprehension
[inner[:6] for inner in my_nested_list] == [
    [ 1,  2,  3,  4,  5,  6],
    [11, 22, 33, 44, 55, 66],
]

However, your data shows a list of lists of lists of lists of string/numeric data so you might need to go deeper:

very_nested_list[0][0][:6] == [
    ['Groningen', 'GM0014', ...],
    ['Amsterdam', 'GM0363', ...],
    ['Utrecht', 'GM0344', ...],
    ['Nijmegen', 'GM0268', ...],
    ['City Five', 'GM5555', ...],
    ['City Six', 'GM6666', ...],  # and no more than 6
]

CodePudding user response:

arr[0][:6]

You can get the lists using slice operator as follows.

  • Related