0

I have this piece of:

As, Bs, Cs, Ds, Es = ([] for i in range(5))
for line in infile:
   line = line.rstrip()
    a, b, c, d, e = line.split('\t')
    As += [a]
    Bs += [b]
    Cs += [c]
    Ds += [d]
    Es += [e]

Since I have many more than just 5, I want to do this with a loop that takes up less lines of code than writing all of it out. Something like:

As, Bs, Cs, Ds, Es = ([] for i in range(5))
dynamic_variable_list = [As, Bs, Cs, Ds, Es]
    for line in infile:
        line = line.rstrip()
        for i in range(len(line.split('\t'))):
            dynamic_variable_list[i] += line.split('\t')[i]

Which in my case stores individual characters in the list, whereas:

dynamic_variable_list[i] += line.split('\t')

Stores all the tab delimited entries into each of the variables of dynamic_variable_list. What I need is to store all of the tab delimited entries in separate variables as the top example shows.

1 Answer 1

1
dynamic_variable_list[i] += line.split('\t')[i]

Can be rewritten as

As += a

Rather than

As += [a]

Either surround in brackets like before, or use append. Or rather, split the list and then make it more clear.

dynamic_variable_list = [As, Bs, Cs, Ds, Es]
    for line in infile:
        columns = line.rstrip().split('\t')
        assert(len(columns)==len(dynamic_variable_list))
        for index, col in enumerate(columns):
            dynamic_variable_list[index].append(col)
Sign up to request clarification or add additional context in comments.

1 Comment

{book = xlrd.open_workbook('file.xls') first_sheet = book.sheet_by_index(0) As, Bs, Cs, Ds, Es = ([] for i in range(5)) dyn_var_list = [As, Bs, Cs, Ds, Es] assert(len(first_sheet.row_values(0))==len(dyn_var_list)) for index, col in enumerate(first_sheet.row_values(0)): dyn_var_list[index].append(col)} however, now I only get the first item in my dyn_var_list. Any suggestions here perhaps? I tried "first_sheet.col_values(0)" and "xrange(1, first_sheet.ncols):"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.