0

I am trying to iterate and separate nested lists. My data input is currently something like this. .

mainlist = [['1', 'HiII', '0', '1407', '0', 'Commander', '11.06.2018'], 
            ['2', 'wEEDzy', '0', '1184', '0', 'Private', '24.03.2021']]

My goal is to use a for loop to separate each list into its own list, then pull specific variables from that list, then output it to a text file. I want to pull only values 1, 3, & 5 from each list.

Now that you know my objective, I am trying to use a for loop to separate each list into its own variable and make that list only those 3 values that are needed.

This is the desired output (each assigned to a variable, then added to a .txt value)

['HiII', '1407', 'Commander']
['wEEDzy','1184', 'Private']

My current code is this: , which separates a list and then adds only the things I want from the list to it.

member1 = list(mainlist[0])
templist = []
templist.append(member1[1])
templist.append(member1[3])
templist.append(member1[5])

What I can't figure out is how to do this for each one for x amount of members so I don't copy and paste it everytime. Can anyone help?

martineau
  • 119,623
  • 25
  • 170
  • 301
frogs114
  • 13
  • 3
  • 1
    You are specifically taking `mainlist[0]`. Just do `for member in mainlist` and then replace `member1` with the loop's variable `member`... Or just do it in a list-comprehension: `new_list = [member[1::2] for member in mainlist]` – Tomerikoo May 01 '21 at 00:27

3 Answers3

0

Use a loop:

for member in mainlist:
    templist = [member[1], member[3], member[5]]
    # do something with templist
Woodford
  • 3,746
  • 1
  • 15
  • 29
0

Assigning to separate variables is usually a bad idea: you have to figure out how to generate and maintain those separate variables. This is why programming languages have lists, dicts, and other data structures. See this link.

Instead, simply extract the data you need into a new list, and iterate through that:

templist = [[member[pos] for pos in (1, 3, 5)] for member in mainlist]

This gives you a similar nested list, with only the desired data.

Now you open your file, iterate through templist, and write the data in your desired format. I trust that you can finish from there?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Prune
  • 76,765
  • 14
  • 60
  • 81
0

You can use slice notation (find a good explanation here: https://stackoverflow.com/a/509295/5239030) within a list comprehension, as already shown by other answers.

Slicing this case: start from index 1 up to the end (stop) in step of two: [1::2].

So, for your list:

mainlist = [['1', 'HiII', '0', '1407', '0', 'Commander', '11.06.2018'], 
            ['2', 'wEEDzy', '0', '1184', '0', 'Private', '24.03.2021']]

Go this way:

tmp = [sublist[1::2] for sublist in mainlist]
#=> [['HiII', '1407', 'Commander'], ['wEEDzy', '1184', 'Private']]

Now that tmp contains the filtered sublists, use it for your purpose.

iGian
  • 11,023
  • 3
  • 21
  • 36