Appending to a new list for every loop - python

I am running a for loop and appending a value into a list for every file run in loop. When I use append(), during the second run through the for loop it appends the new values into the same list as in the first run through loop. Is there a way to append and create a new list everytime it runs through loop?
phaseresult_i =[]
for i in range(len(folder)):
data = np.loadtxt(dir + folder[i])
time = data[:,0]-2450000
magnitude = data[:,1]
print ('File:', folder[i],'\n','Time:',time,'\n', 'Magnitude:', magnitude)
print(len(time), len(magnitude))
for t in range(len(time)):
#print(t,time[t])
floor = math.floor((time[t]-time[0])/Period)
phase_i = ((time[t]-time[0])/Period)-floor
phaseresult_i.append(phase_i)
print(len(time), len(phaseresult_i))
The length of the array of time and length of array of phase result is not the same after the second time through loop.

An mcve for creating a new list on each iteration of the outer loop then append to that list in the inner loop.
x = []
for n in range(4):
q = []
x.append(q)
#other stuff
for t in range(10):
#other stuff
q.append(t)
>>> from pprint import pprint
>>> pprint(x)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>>

Related

Sum of every element in a list

So i have a list:
list1 = [[1, 3, 6, 8, 9, 9, 12], [1, 2, 3, 2, 1, 0, 3, 3]]
but you can also split it into two lists, if it make it any easier. All i have to do is sum every digit with every other digit. Like you know
first row:
1+1, 1+2, 1+3, 1+2, 1+1...
second:
3+1... etc.
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]
w = [x + y for x, y in zip(first, second)]
I was trying to do it in this way. But it doesn't work*, any ideas?
*i mean its summing in a wrong way, instead of every possible digits with every possible, just the first one in 1st list with 1st in second list.
zip is getting only pairs that sit at the same index. You should instead have a double loop:
[x + y for x in first for y in second]
You can do it using itertools to get all possible pair then make a pair of sum list
import itertools
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]
res = itertools.product(first, second)
ress = [sum(pair) for pair in res]
print(ress)

problems in my list sorting code in python

I've come up with this code to sort out duplicates in a randomly arranged list of numbers.
counter = 0
randomDup_list = [0, 3, 0, 1, 9, 8, 2, 3, 4, 2, 4, 3, 5, 6, 0, 6, 5, 2, 6, 6, 7, 8, 9, 4, 4]
dup_sorted = []
for x in randomDup_list:
if len(randomDup_list) == 0:
dup_sorted.append(x)
counter +=1
elif x != randomDup_list[counter]:
for y in dup_sorted:
if y != x:
dup_sorted.append(x)
print(dup_sorted)
When I run the code there are no errors but the numbers don't seem to be appending to my new list, and it comes out blank like this: [].
The most pythonic way to do this is with a list comprehension, like so:
dup_sorted = [el for index, el in enumerate(randomDup_list) if el not in randomDup_list[:index]]
Enumerate will create a list of tuples with the first tuple element as the index in the list, [(0,0), (1,3), (2,0), ...] are the first 3 elements in your case.
Then it basically checks if el is the first occurence of el in the list and if it is, it adds el to the dup_sorted list.
List comprehensions are maybe hard to understand, but there is plenty of information about them on the internet. Good luck with learning Python!
I did not understand what you want but you can basically sort the list like that
print(sorted(randomDup_list))
and you can create your new list like that
dup_sorted = sorted(randomDup_list)
print(dup_sorted)
Hey welcome to learning python. I have been coding for a couple of years but I still use print to test my logic.
Lets break down your code and add print to each logic test
counter = 0
randomDup_list = [0, 3, 0, 1, 9, 8, 2, 3, 4, 2, 4, 3, 5, 6, 0, 6, 5, 2, 6, 6, 7, 8, 9, 4, 4]
dup_sorted = []
for x in randomDup_list:
print("start iteration")
if len(randomDup_list) == 0:
print("1 true")
dup_sorted.append(x)
counter +=1
elif x != randomDup_list[counter]:
print("2 true")
print(dup_sorted)
for y in dup_sorted:
if y != x:
print("3 true")
dup_sorted.append(x)
print("stop iteration")
print(dup_sorted)
If you run this code you will see that the first logic test will never be true in your example. So it will go to the second logic test. This will eventually evaluate to true but there will be some iterations that will be skipped. Blank blocks of start iteration stop iteration. For the last logic test this will never be true because dup_sorted will always be empty. So for y in dup_sorted will result to nothing.
Also I think sort out is ambiguous. Is it sort? filter?
You can do set(randomDup_list) for filtering out duplicates
You can do sorted(randomDup_list) for sorting out the list
You can do sorted(list(set(randomDup_list)) for a sorted filtered list
Seeing your new comments
randomDup_list = [0, 3, 0, 1, 9, 8, 2, 3, 4, 2, 4, 3, 5, 6, 0, 6, 5, 2, 6, 6, 7, 8, 9, 4, 4]
dup_sorted = []
for x in randomDup_list:
if x in dup_sorted:
continue
else:
dup_sorted.append(x)
print(dup_sorted)
This initializes an empty list. Loops through your list. Check if it exists then appends if not. Since List maintain order, you can expect the order not to change.
To remove any duplicates from the list without changing the order
Code
dup_sorted = []
for x in randomDup_list:
if not x in dup_sorted: # check if x is in output yet
dup_sorted.append(x) # add x to output
print(dup_sorted)
# Output: [0, 3, 1, 9, 8, 2, 4, 5, 6, 7]
You can use this:
counter = 0
randomDup_list = [0, 3, 0, 1, 9, 8, 2, 3, 4, 2, 4, 3, 5, 6, 0, 6, 5, 2, 6, 6, 7, 8, 9, 4, 4]
dup_sorted = []
dup_sorted.append(randomDup_list[0])
for x in range(len(randomDup_list)):
temp = 0
for y in range(len(dup_sorted)):
if randomDup_list[x] != dup_sorted[y]:
temp = temp + 1
if temp == len(dup_sorted):
dup_sorted.append(randomDup_list[x])
print(dup_sorted)

Python move all elements of a list one position back with same len

def list_move_back(new_value, value_list):
for i in reversed(value_list):
if value_list.index(i) != len(value_list)-1:
value_list[value_list.index(i)+1] = i
value_list[0] = new_value
return value_list
I want to get the following result:
list_example = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_example = list_move_back(12, list_example]
print(list_example)
>>>[12, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It works if I run the function two times:
list_example = list_move_back(12, list_example]
print(list_example)
>>>[12, 12, 1, 2, 3, 4, 5, 6, 7, 8]
but if I want to run it a third time, the result looks like that:
list_example = list_move_back(12, list_example]
print(list_example)
>>>[12, 12, 1, 1, 3, 4, 5, 6, 7, 8]
The first 1 should be a 12. I have no idea why it doesn't work.
Just use list slicing:
def list_move_back(new_value, list_of_values):
return [new_value] + list_of_values[:-1]
Explanation: list_of_values[:-1] returns all the elements except for the last. By appending it to the new value, you get the wanted result. This answer has a pretty cool explanation of how list slicing works.
Also, if for some reason you'd like the "verbose" way to do this (maybe for an exercise or whatever), here's a way to go about it:
def list_move_back(new_value, list_of_values):
for i in range(len(list_of_values)-1, 0, -1):
list_of_values[i] = list_of_values[i-1]
list_of_values[0] = new_value
return list_of_values
I'd recommend list slicing over this method 9/10 times but again, I'm just leaving this here because there might be a case where someone wants to do this as some sort of mental exercise for indexing.
If you need the list to change in place, you can use the list methods .pop() to remove the last item and .insert(0,value) to add an item to the front:
>>> L = list(range(1,11))
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> id(L)
1772071032392
>>> L.pop();L.insert(0,12)
10
>>> L
[12, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> id(L) # same list id, modified in place...
1772071032392

separating numbers with coma in python

I am building a sudoku game, I found a site that can provide me 1 million pre generated games.
I downloaded the file (CSV) and want to prepare it for frontend use.
Each game is 81 numbers like
346179258187523964529648371965832417472916835813754629798261543631485792254397186
974183652651274389283596714129835476746912538835647921568329147317468295492751863
563472198219386754847195623472638519951247386638519472795864231324951867186723945
I would love to create JS or JSON file with all the puzzles in order to import it in my code.
Here is the ideal result for each game (line).
[
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]
Here is what I managed to accomplish in python
import csv
import json
holder = []
rows = []
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
with open('sudoku.csv', newline='') as csvfile:
counter = 0
n = 9
s=','
reader = csv.DictReader(csvfile)
for row in reader:
if counter > 10:
break
print(row['solutions'])
print(len(row['solutions']))
test = [int(str(row['solutions']))]
#chunk = divide_chunks(test, n)
# for val in enumerate(chunk):
# val = [val]
# # for index,item in enumerate(val):
# # item[index] = item+s
# # print(val)
holder.append(test)
counter +=1
print(holder)
with open('puzzles.json', 'w') as outputfile:
json.dump(holder,outputfile)
this is my output so far in puzzles.json
[
[864371259325849761971265843436192587198657432257483916689734125713528694542916378],
[346179258187523964529648371965832417472916835813754629798261543631485792254397186],
[695127384138459672724836915851264739273981546946573821317692458489715263562348197],
[497258316186439725253716498629381547375964182841572639962145873718623954534897261],
[465912378189473562327568149738645291954821637216397854573284916642159783891736425],
[194685237382974516657213489823491675541768923769352841215839764436527198978146352],
[289765431317924856645138729763891542521473968894652173432519687956387214178246395],
[894231657762495183351876942583624719219387564647159328128763495976542831435918276],
[563472198219386754847195623472638519951247386638519472795864231324951867186723945],
[163725948584693271729184365946358127371462589852917634498231756637549812215876493],
[974183652651274389283596714129835476746912538835647921568329147317468295492751863]
]
Any suggestions please?
Thanks
You can break the string into numbers by using a list comprehension
sudoku = 346179258187523964529648371965832417472916835813754629798261543631485792254397186
sudoku_list = [number for number in str(sudoku)]
And then you break that into chunks of length 9 by using another list comprehension
sudoku_final = [sudoku_list[9*i:9*i+9] for i in range(9)]
If you want the output to be integers instead of strings, use int(number) for number in str(sudoku) in the list comprehension
Using Python, you can separate all the numbers into a list by converting them into a string and back like so:
tuple(map(int, str(x))) # x is the 81 digit number.
With that, you can separate the list of 81 digits into a 9x9 grid like so (iterating through every multiple of 9 and taking the next 9 numbers):
[x[i: i + 9] for i in range(0, 81, 9)]

How to store a randomly generated 2-D list from a while loop?

I am unable to store unique 1D list into a 2D list.
I'm having trouble storing multiple randomly generated list into a 2D list. I can generate n number of unique 1D generated lists but when I try to store them in a 2D list, I get the same 1D list generated n number of time.
I've used the append() function on the list but instead get the same 1D list appended multiple times.
I've used the extend() function but it returns a 1D list.
I don't understand why the object is aliased when I'm using the shuffle() function.
import random
bd = list(range(10))
rng = random.Random()
rng.shuffle(bd)
d_list = []
number = 0
while number < 5:
d_list.append(bd)
number += 1
print(d_list)
I expected the results to be
[[6, 5, 3, 8, 2, 4, 0, 9, 1, 7],[7, 6, 9, 8, 5, 3, 4, 0, 2, 1], [2, 1, 0, 7, 3, 8, 6, 5, 4, 9], [1, 2, 7, 0, 3, 4, 5, 6, 8, 9],[7, 6, 3, 8, 4, 5, 1, 9, 0, 2]]
but instead the results are
[[7, 6, 3, 8, 4, 5, 1, 9, 0, 2], [7, 6, 3, 8, 4, 5, 1, 9, 0, 2], [7, 6, 3, 8, 4, 5, 1, 9, 0, 2], [7, 6, 3, 8, 4, 5, 1, 9, 0, 2], [7, 6, 3, 8, 4, 5, 1, 9, 0, 2]]
In your code:
while number < 5:
d_list.append(bd). #bd is the same and initialized one time
number += 1
You need to execute the randomizer within the while for you to truly have random lists each time.
Move your initialization of bd to your loop:
import random
d_list = []
number = 0
while number < 5:
bd = list(range(10))
rng = random.Random()
rng.shuffle(bd)
d_list.append(bd)
number += 1
print(d_list)
Right now, you're shuffling and adding the same list to d_list 5 times. Initializing the list inside the loop means that you're actually creating 5 different lists.
To solve your problem, shuffle bd at every iteration or use this one-liner to generate the same list:
d_list = [random.sample(range(10), 10) for i in range(5)]
It seems that you're appending 5 times the same list to an empty list. The result shows exactly that.
If you want a new random list to be generated at every iteration, I would recommend placing the list shuffle inside the loop.
import random
bd = list(range(10))
rng = random.Random()
rng.shuffle(bd)
d_list = []
number = 0
while number < 5:
rng.shuffle(bd)
d_list.append(bd)
number += 1
Note: I owuld also recomment using a for loop instead of a while info :
import random
bd = list(range(10))
rng = random.Random()
rng.shuffle(bd)
d_list = []
for range(5):
rng.shuffle(bd)
d_list.append(bd)

Categories