Appending elements in a list using for Loop - python-3.x

I want to append elements in a list using a for loop. This is the code:
outdoor_temp_list = []
indoor_temp_list = []
energy_cons_list = []
outdoor_temp_list.append(30+i)
indoor_temp_list.append(20+i)
energy_cons_list.append(200+i)
However, it is not appending in each iteration (30, 31, 32, 33, ...), but this the output:
[34] [24] [204]
I did not understand how it is working, I would appreciate any help!

Define list outside.other wise if you are running the code like
for i in range(5):
outdoor_temp_list = []
indoor_temp_list = []
energy_cons_list = []
outdoor_temp_list.append(30 + i)
indoor_temp_list.append(20 + i)
energy_cons_list.append(200 + i)
print(outdoor_temp_list,indoor_temp_list,energy_cons_list)
you will get output only for the last iteration. because during each iteration you are initializing it by []
[34] [24] [204]
so you have to initialize it before the for loop
outdoor_temp_list = []
indoor_temp_list = []
energy_cons_list = []
for i in range(5):
outdoor_temp_list.append(30 + i)
indoor_temp_list.append(20 + i)
energy_cons_list.append(200 + i)
print(outdoor_temp_list,indoor_temp_list,energy_cons_list)
then you will get the desire output like
[30, 31, 32, 33, 34] [20, 21, 22, 23, 24] [200, 201, 202, 203, 204]

Related

Transformation of dictionary to numpy array generates incorrect values within loop

I need to transform dicts from a generator object to a numpy array within a loop.
But all approaches known to me lead to identically incorrect values. Here's my recent code at the crucial point:
...
i = 0
while time.time() < t+st:
genob = next(gen)
keys = np.fromiter(genob.keys(), dtype=int)
vals = np.fromiter(genob.values(), dtype=int)
if i == 0:
mytest1 = genob
mytest2 = keys
mytest3 = vals
i = 1
...
...
What I'm trying to do here is: get the dict generator object and get the values out for further usage. I get no errors, but the results are not as expected:
First lines of result mytest1 = genob:
mytest1: {0: 29, 1: 29, 2: 0, 3: 31, 4: 30, 5: 30, 6: 29, 7: 29, 8: 29, 9: 0, 10: 29, ...}
First lines of result mytest2 = keys:
mytest2: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...])
First lines of result mytest3 = vals:
mytest3: array([ 31, 0, 30, 30, 29, 28, 30, 29, 0, 29, 0, ...])
--> Keys are in correct order, but I do not receive correct key-value pairs. Why np.fromiter does not give me the correct values? If I use a transformation via dict.items and list or list comprehension or ... I get the identical incorrect result.
Now, magically, if I use
np.fromiter(mytest1.values(), dtype = int)
outside of my loop, the expected result is calculated:
array([ 29, 29, 0, 31, 30, 30, 29, 29, 29, 0, 29, ...])
Unfortunately, this does only happen outside the loop - within the loop it does not help to transform via mytest1...
Kernel and / or windows restart do not change a thing.
Using float datatypes does not change a thing.
Does anybody have an idea what the problem might be?
Thanks for any help!
System information:
system='Windows', release='10', version='10.0.19041', machine='AMD64', processor='Intel64 Family 6 Model 58 Stepping 9, GenuineIntel'
Python 3.8.8 via conda 4.11.0 in ipynb; numpy 1.20.1
Additions:
Creation of Mini-Example: Works as expected - problem is only reproducable in full code.
Mini-Example:
import random
from statistics import mean
import numpy as np
import time
def MyGen(loop_time):
start_time = time.time()
while time.time() <= start_time + loop_time:
v = 500
n = 0
#create empty dict
mydict = {}
#create dict entries as lists
for i in range(360):
mydict.update({i:[]})
#create entries for lists in correspondence to keys
mykeys = [random.randint(0,360-1) for i in range(v)]
myvals = [random.randint(1,100) for i in range(v)]
#allocate values in dict
for i in mykeys:
mydict[i].append(myvals[n])
n = n+1
#calculate mean in dict
for i in mydict.keys():
if len(mydict[i]) > 0:
mydict[i]=int(mean(mydict[i]))
else:
mydict[i]=0
yield mydict
loop_time = 4
start_time = time.time()
i = 0
gen = MyGen(loop_time)
counter = 0
while time.time() <= start_time + loop_time:
genob = next(gen)
keys = np.fromiter(genob.keys(), dtype=int)
vals = np.fromiter(genob.values(), dtype=int)
if i == 0:
mytest1 = genob
mytest2 = keys
mytest3 = vals
i = 1
counter = counter + 1
print(counter)

how to create a list of strings consisting of strings and integers?

that's a basic one but I'm stuck.
I want to create a list with combined strings and numbers like [df_22, df_23, ... df_30].
I have tried
def createList(r1, r2):
return str(list(range(r1, r2+1)))
so it gives me a list of numbers:
In: mylist = createList(2, 30)
In: mylist
Out: '[22,23, 24, 25, 26, 27, 28, 29, 30]'
I am not sure how to add 'df_' to it because 'return df + str(list(range(r1, r2+1)))' gives an UFuncTypeError.
and
def createList(r1, r2):
res = 'df_'
return res + str(list(range(r1, r2+1)))
In: mylist = createList(22, 30)
In: mylist
Out: 'df_[22, 23, 24, 25, 26, 27, 28, 29, 30]'
I need my list to be
mylist
Out: [df_22, df_21, ... df_30]
This does what your title seems to describe:
def createList(r1, r2):
return str(['df_%d'%x for x in range(r1, r2+1)])

Is there a more simple way to convert a string of sequence of numbers to a list in python?

I have this string x = "1-3,5,7,11-16,20"
and I want to transform it to a list of integers like this:
[1,2,3,5,7,11,12,13,14,15,16,20].
I wrote this code and it does work:
def page_range(x):
p = x.split(',')
d = list()
nums = list()
for i in range(0,len(p)):
d.append(p[i].find('-'))
for i in range(0,len(d)):
if d[i] >= 1:
z,y = p[i].split('-')
nums = nums + list(range(int(z),int(y)+1))
else:
nums.append(int(p[i]))
return nums
But is there a more simple way to do that?
This is one approach
x = "1-3,5,7,11-16,20"
res = []
for i in x.split(","):
if "-" in i:
s, e = i.split("-")
res.extend(range(int(s), int(e)+1))
else:
res.append(int(i))
print(res)
Output:
[1, 2, 3, 5, 7, 11, 12, 13, 14, 15, 16, 20]
This is simpler if you define a function to convert a string like 12 or 4-5 into the numbers it represents:
def str_to_nums(s):
if '-' in s:
a, b = map(int, s.split('-'))
return range(a, b+1)
else:
return int(s), # comma makes this a one-element tuple
Then you can use a list comprehension:
>>> [n for s in x.split(',') for n in str_to_nums(s)]
[1, 2, 3, 5, 7, 11, 12, 13, 14, 15, 16, 20]
This could also be tried:
ls = []
for i in x.split(','):
if i.isdigit() != 1:
r1, r2 = i.split('-')
ls.extend(range(int(r1), int(r2)+1))
else:
ls.append(int(i))

A problem with printing spiral list in python

I have a problem with making a spiral list.
The program should output a table of size n × n, filled with numbers from 1 to n * n in a spiral coming from the upper-left corner in a clockwise fashion, as shown in the example (here n = 5)
It works when n is even and doesn't work when n is odd
n = int(input())
arr = [[0 for i in range(n)] for j in range(n)]
stop = 0
start = 0
elem = 1
while elem <= n*n:
stop += 1
for j in range(start, n-stop):
i = start
arr[i][j] = elem
elem += 1
for i in range(start, n-stop):
j = n-stop
arr[i][j] = elem
elem += 1
for j in range(n-stop, start, -1):
i = n-stop
arr[i][j] = elem
elem += 1
for i in range(n-stop, start, -1):
j = start
arr[i][j] = elem
elem += 1
start += 1
for i in range(len(arr)):
for j in range(len(arr)):
print(arr[i][j], end=' ')
print()
Help please, where can be problem here?
You can use numpy:
import numpy as np
def spiral(n=5):
a = np.arange(n*n)
b = a.reshape((n,n))
m = None
for i in range(n, 0, -2):
m = np.r_[m, b[0, :], b[1:, -1], b[-1, :-1][::-1], b[1:-1, 0][::-1]]
b = b[1:-1, 1:-1]
a[list(m[1:])]=list(a)
return a.reshape((n,n)) + 1
spiral()
array([[ 1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]])
spiral(10)
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[ 36, 37, 38, 39, 40, 41, 42, 43, 44, 11],
[ 35, 64, 65, 66, 67, 68, 69, 70, 45, 12],
[ 34, 63, 84, 85, 86, 87, 88, 71, 46, 13],
[ 33, 62, 83, 96, 97, 98, 89, 72, 47, 14],
[ 32, 61, 82, 95, 100, 99, 90, 73, 48, 15],
[ 31, 60, 81, 94, 93, 92, 91, 74, 49, 16],
[ 30, 59, 80, 79, 78, 77, 76, 75, 50, 17],
[ 29, 58, 57, 56, 55, 54, 53, 52, 51, 18],
[ 28, 27, 26, 25, 24, 23, 22, 21, 20, 19]])
A better way would be to import pdb and step through your program with a debugger. Instead, I just added some extra print statements:
n = 5
arr = [[0 for i in range(n)] for j in range(n)]
stop = 0
start = 0
elem = 1
count = 0
while elem <= n*n:
stop += 1
for j in range(start, n-stop):
i = start
arr[i][j] = elem
print('a')
elem += 1
for i in range(start, n-stop):
j = n-stop
arr[i][j] = elem
print('b')
elem += 1
for j in range(n-stop, start, -1):
i = n-stop
arr[i][j] = elem
print('c')
elem += 1
for i in range(n-stop, start, -1):
j = start
arr[i][j] = elem
print('d')
elem += 1
print('e')
count +=1
if count > 50:
break
start += 1
for i in range(len(arr)):
for j in range(len(arr)):
print(arr[i][j], end=' ')
print()
Here's the output I got:
a
a
a
a
b
b
b
b
c
c
c
c
d
d
d
d
e
a
a
b
b
c
c
d
d
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
1 2 3 4 5
16 17 18 19 6
15 24 0 20 7
14 23 22 21 8
13 12 11 10 9
It looks like something about odd values of n is allowing each for loop to complete, but elem doesn't get incremented enough so your while loop is running forever.
This looks like homework or a coding challenge, so I'm not going to go too deep into why, but I hope I've given you a hint.

How to remove ending commas in a list of ints with python?

I have a function I wrote in python that simple makes a horizontal list of int. I modified the print statement so that the list would print with commas, but the function adds one after the last int.
Any ideas as how to get rid of it?
num = list(range(20))
def count(x):
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
print(i+1,end=',')
count(num)
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
Try this:
num = list(range(20))
l = []
def count(x):
for i in range(len(x)):
l.append(i+1)
count(num)
print(l)
Outpout:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20]
You can also modify it to this:
def count(x):
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
if i < len(x)-1:
print(i+1, end=',')
else:
print(i+1)
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Try this:
num = list(range(20))
def count(x):
for i in range(len(x)-1):
print(i+1,end=',')
print(len(x))
count(num)
Add each number to a string and then print the string minus the last character:
num = list(range(20))
def count(x):
s = ""
for i in range(len(x)):
# i+1 add in order to remove beginning zero.
s += str(i+1) + ","
print(s[:-1])
count(num)
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
A better function name would be display, and the function you want is str.join():
def display(list_data):
print(', '.join(list_data))
The thing to keep in mind is the pieces to join must be strings, so you may need to convert:
', '.join([str(i) for i in list_data])
Rather than creating a function, an output sequence can be processed with the range command:
num = range(1,21,1)
print num
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Print without the braces:
num = range(1,21,1)
print str(num).strip('[]')
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
User chooses start and ending numbers somewhere earlier in the code:
start = 56
end = 69
num = range(start, end + 1)
print str(num).strip('[]')
Output is:
56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69
User supplies start and stop interactivly:
start = raw_input('Choose start')
end = raw_input('Choose end')
num = range(start, end + 1)
print str(num).strip('[]')

Resources