0

I am making a code which needs me to move the first variable of every list I have into one single list.

For example:

Week1 = [2,3,4,5,6]
Week2 = [3,2,5,6,4]
# I would need to get a list that read
Week_1 = [2,3]

This would be on quite a large scale wit 20 or so variables. I have an idea in mind:

Week1 = [0, 1, 2, 2, 1]
Week2 = [4, 3, 1, 6, 3]
Week = []
i = 1
while i >= 20:
    Week = Week.extend((Week + i) [0])
    i = i + 1



print (Week)

This probably won't work i know, but would it be possible for the 'week + i' to relate to the variable, so the code would extend by 'Week1 [0]'? This would mean that as the loop progresses it would add the first variable of each list to the other list I believe. Are there any more efficient ways of doing this? Or is there a way for this to work?

  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Carcigenicate Apr 03 '19 at 17:49
  • What happens though when `i` is 3 or more (or 0). You don't have lists for those numbers. – Carcigenicate Apr 03 '19 at 17:50

2 Answers2

0

Assuming your lists are stored in separate variables that are named in following format Week[week number], you could iterate over specific amount of weeks (here 2) and access values of your variables via globals() to append them to some list, here first_values.

Week1 = [2,3,4,5,6]
Week2 = [3,2,5,6,4]

first_values = []
weeks = 2

for week in range(1, weeks + 1):
    first_values.append(globals()['Week{}'.format(week)][0])

print(first_values) # --> [2, 3]
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
0

You have two questions at work here. First, to access the first values from each list at the same time and so on, you can use a zip.

Secondly, You can use either a list or a dict to create and collect all the results for each week as necessary. Instead of making a variable number of variables, use a container that is able to hold as many Weeks as needed.

A solution may look like this:

Week1 = [2,3,4,5,6]
Week2 = [3,2,5,6,4]
initial_list = [Week1, Week2]

Week_dict = {}
for i, Week in enumerate(zip(*initial_list)):
    Week_dict["Week_{}".format(i + 1)] = Week

print(Week_dict)
#Output:
{'Week_1': (2, 3),
 'Week_2': (3, 2),
 'Week_3': (4, 5),
 'Week_4': (5, 6),
 'Week_5': (6, 4)}
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33