[Fixed]-How to exclude some indexes in a python loop?

1πŸ‘

βœ…

l = [ [ 1, "EEBC92F4-DA8C-4B58-8730-3119F6B1C045", 1, 1386882230, "399231", 1386882230, "399231", "{\n}", "2010", "NON-HISPANIC BLACK", "MALE", "HUMAN IMMUNODEFICIENCY VIRUS DISEASE", "297", "5" ],
    [ 2, "84C91A4A-19E2-4AD2-9493-17B84707CA4E", 2, 1386882230, "399231", 1386882230, "399231", "{\n}", "2012", "NON-HISPANIC BLACK", "MALE", "INFLUENZA AND PNEUMONIA", "2011", "3" ]]

#get index of the year
l[0].index('2010') #8
l[1].index('2012') #8

In case you only want to print you can do:

for x in l:
    for el in x[8:]:
        print el

which gives you the following output:

2010
NON-HISPANIC BLACK
MALE
HUMAN IMMUNODEFICIENCY VIRUS DISEASE
297
5
2012
NON-HISPANIC BLACK
MALE
INFLUENZA AND PNEUMONIA
2011
3

Not fully sure whether that is what you want but you wrote that you need all the information after the respective years (β€œI’m referring about all the information after the year in every row.”, your reply to James in the comments) so you could first extract these elements and store them in a new list (in case you want to do something else with them except of printing):

lmod = [x[8:] for x in l]

lmod then looks like this:

[['2010',
  'NON-HISPANIC BLACK',
  'MALE',
  'HUMAN IMMUNODEFICIENCY VIRUS DISEASE',
  '297',
  '5'],
 ['2012',
  'NON-HISPANIC BLACK',
  'MALE',
  'INFLUENZA AND PNEUMONIA',
  '2011',
  '3']]

This can now be printed as you did it:

for sl in lmod:
   for el in sl:
       print el

Output:

2010
NON-HISPANIC BLACK
MALE
HUMAN IMMUNODEFICIENCY VIRUS DISEASE
297
5
2012
NON-HISPANIC BLACK
MALE
INFLUENZA AND PNEUMONIA
2011
3

Is that what you were looking for?

πŸ‘€Cleb

0πŸ‘

You didn’t really give a great example, but you can use a generator:

filteredList = (x for x in list if int(x[8]) >= 2010)
for a in filteredList:
    for b in a:
        print b

Or, you can write it more directly:

for a in (x for x in list if int(x[8]) >= 2010):
    for b in a:
        print b

Though, you might want your β€œrecords” here to be dicts instead of lists.

πŸ‘€rlbond

0πŸ‘

for a in mylist:
    if int(a[8]) > 2009:
        for b in a:
            print b,
        print

This goes through each item in mylist (renamed from the list that masks the built-in), checks if the element at index 8 is greater than 2009, and then prints out the item’s elements separated by a single space. If you want more control over the output, use string formatting.

πŸ‘€TigerhawkT3

Leave a comment