Accessing array items - python

I've got a list that is one dimensional that I need separated by spaces. I am running this script in spyder for ubuntu running on parallels on Mac OS 10.8.
what I'm getting is this:
print poly
Output: [array([ 0.01322341, 0.07460202, 0.00832512])]
print poly[0]
Output: [array([ 0.01322341, 0.07460202, 0.00832512])]
print poly[1]
Output:
Traceback (most recent call last):
File "/home/parallels/.../RampEst.py", line 38, in <module>
print poly[1]
IndexError: list index out of range
The "..." is the rest of the file directory.
What I need is:
print poly[0]
Output: 0.01322341
print poly[1]
Output: 0.07460202
print poly[2]
Output: 0.00832512

You are constructing your list objects in the wrong way. If you post where you're doing that it might be clear as to the actual problem.
You'll notice that the following:
mylist = [ 0.01322341, 0.07460202, 0.00832512]
mylist[0] # 0.01322341
mylist[1] # 0.07460202
mylist[2] # 0.00832512
Works fine. From what you're posted, you have a list of array types. When you access the 0 element you are retrieving the only array object in the list. If you can't change the structure of your list, this will work fine.
poly[0][0] # 0.01322341
poly[0][1] # 0.07460202
poly[0][2] # 0.00832512

How do you first initialize poly?
It seems that the array is within a list, which would make it the zeroth element of the list. Therefore, when you request poly[1] it fails.
To check if what I am saying is correct, do poly[0][0], poly[0][1] and poly[0][2]. If these return the numbers you want, then your poly is inside a list.

Related

Creating a Tuple made of variable strings

The following code works:
image_files=['imgpy1.png','imgpy2.png']
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=20)
But I have 200 filenames 'imgpy1.png', 'imgpy2.png' and so on. How do I create an object called image_files, that contain these file names. I tried to create an array of strings:
flist=[]
flist=list(map(str,flist))
flist.append['imagepy1.png']
flist.append['imagepy2.png']
but that does not work. I get the error message
Traceback (most recent call last):
File "C:\Users\vince\image.py", line 53, in <module>
flist.append['imagepy1.png']
TypeError: 'builtin_function_or_method' object is not subscriptable
I am new to Python and can't figure out how to get an array or Tuple of strings. I've tried for 2-3 hours to non avail, at least 40 different ways including stuff I read online that don't work on my laptop. In the end, I am only interested in passing an argument to the video function that (1) does not crash the Python interpreter and (2) can be digested by the video function. So far, I am stuck with (1). But in the end I'm looking at solving (2). I don't care if it's an array, a list, a Tuple or anything else, as long as it works.
I think append function is not correct.
flist.append('imagepy1.png') # not brackets
flist.append('imagepy2.png')
flist = []
for i in range(200):
flist.append(f"imagepy{i + 1}.png") #you use square brackets not round ones
print(flist)
this gets you
['imagepy1.png', 'imagepy2.png', 'imagepy3.png', 'imagepy4.png', 'imagepy5.png', 'imagepy6.png', 'imagepy7.png', 'imagepy8.png', 'imagepy9.png', 'imagepy10.png', 'imagepy11.png', 'imagepy12.png', 'imagepy13.png', 'imagepy14.png', 'imagepy15.png', 'imagepy16.png', 'imagepy17.png', 'imagepy18.png', 'imagepy19.png', 'imagepy20.png', 'imagepy21.png', 'imagepy22.png', 'imagepy23.png', 'imagepy24.png', 'imagepy25.png', 'imagepy26.png', 'imagepy27.png', 'imagepy28.png', 'imagepy29.png', 'imagepy30.png', 'imagepy31.png', 'imagepy32.png', 'imagepy33.png', 'imagepy34.png', 'imagepy35.png', 'imagepy36.png', 'imagepy37.png', 'imagepy38.png', 'imagepy39.png', 'imagepy40.png', 'imagepy41.png', 'imagepy42.png', 'imagepy43.png', 'imagepy44.png', 'imagepy45.png', 'imagepy46.png', 'imagepy47.png', 'imagepy48.png', 'imagepy49.png', 'imagepy50.png', 'imagepy51.png', 'imagepy52.png', 'imagepy53.png', 'imagepy54.png', 'imagepy55.png', 'imagepy56.png', 'imagepy57.png', 'imagepy58.png', 'imagepy59.png', 'imagepy60.png', 'imagepy61.png', 'imagepy62.png', 'imagepy63.png', 'imagepy64.png', 'imagepy65.png', 'imagepy66.png', 'imagepy67.png', 'imagepy68.png', 'imagepy69.png', 'imagepy70.png', 'imagepy71.png', 'imagepy72.png', 'imagepy73.png', 'imagepy74.png', 'imagepy75.png', 'imagepy76.png', 'imagepy77.png', 'imagepy78.png', 'imagepy79.png', 'imagepy80.png', 'imagepy81.png', 'imagepy82.png', 'imagepy83.png', 'imagepy84.png', 'imagepy85.png', 'imagepy86.png', 'imagepy87.png', 'imagepy88.png', 'imagepy89.png', 'imagepy90.png', 'imagepy91.png', 'imagepy92.png', 'imagepy93.png', 'imagepy94.png', 'imagepy95.png', 'imagepy96.png', 'imagepy97.png', 'imagepy98.png', 'imagepy99.png', 'imagepy100.png', 'imagepy101.png', 'imagepy102.png', 'imagepy103.png', 'imagepy104.png', 'imagepy105.png', 'imagepy106.png', 'imagepy107.png', 'imagepy108.png', 'imagepy109.png', 'imagepy110.png', 'imagepy111.png', 'imagepy112.png', 'imagepy113.png', 'imagepy114.png', 'imagepy115.png', 'imagepy116.png', 'imagepy117.png', 'imagepy118.png', 'imagepy119.png', 'imagepy120.png', 'imagepy121.png', 'imagepy122.png', 'imagepy123.png', 'imagepy124.png', 'imagepy125.png', 'imagepy126.png', 'imagepy127.png', 'imagepy128.png', 'imagepy129.png', 'imagepy130.png', 'imagepy131.png', 'imagepy132.png', 'imagepy133.png', 'imagepy134.png', 'imagepy135.png', 'imagepy136.png', 'imagepy137.png', 'imagepy138.png', 'imagepy139.png', 'imagepy140.png', 'imagepy141.png', 'imagepy142.png', 'imagepy143.png', 'imagepy144.png', 'imagepy145.png', 'imagepy146.png', 'imagepy147.png', 'imagepy148.png', 'imagepy149.png', 'imagepy150.png', 'imagepy151.png', 'imagepy152.png', 'imagepy153.png', 'imagepy154.png', 'imagepy155.png', 'imagepy156.png', 'imagepy157.png', 'imagepy158.png', 'imagepy159.png', 'imagepy160.png', 'imagepy161.png', 'imagepy162.png', 'imagepy163.png', 'imagepy164.png', 'imagepy165.png', 'imagepy166.png', 'imagepy167.png', 'imagepy168.png', 'imagepy169.png', 'imagepy170.png', 'imagepy171.png', 'imagepy172.png', 'imagepy173.png', 'imagepy174.png', 'imagepy175.png', 'imagepy176.png', 'imagepy177.png', 'imagepy178.png', 'imagepy179.png', 'imagepy180.png', 'imagepy181.png', 'imagepy182.png', 'imagepy183.png', 'imagepy184.png', 'imagepy185.png', 'imagepy186.png', 'imagepy187.png', 'imagepy188.png', 'imagepy189.png', 'imagepy190.png', 'imagepy191.png', 'imagepy192.png', 'imagepy193.png', 'imagepy194.png', 'imagepy195.png', 'imagepy196.png', 'imagepy197.png', 'imagepy198.png', 'imagepy199.png', 'imagepy200.png']
is this what you were looking for?

Python code went wrong for my optimization problem

I am new in using python. I tried to write a code for my optimization research model. Could you help me please? I don't know what's wrong with the code. I am using python 2 by the way. Thank you.
for i in range(len(lift)):
prob+=lpSum(dec_var[i])<=1
#constraints
col_con=[1,0,0,2,2,3,1,1]
dec_var=np.array(dec_var)
col_data=[]
for j in range(len(brands)):
col_data.append(list(zip(*dec_var)[j]))
prob+=lpSum(col_data[j])<=col_con[j]
#problem
prob.writeLP("SO.lp")
#solve the problem
prob.solve()
print("The maximum Total lift obtained is:",value(prob.objective)) # print the output
#print the decision variable output matrix
Matrix=[[0 for X in range(len(lift[0]))] for y in range(len(lift))]
for v in prob.variables():
Matrix[int(v.name.split("_")[2])][int(v.name.split("_")[3])]=v.varValue
matrix=np.int_(Matrix)
print ("The decision variable matrix is:")
print(matrix)
the error was :
TypeError Traceback (most recent call
last) in
13 for j in range(len(brands)):
14
---> 15 col_data.append(list(zip(*dec_var)[j]))
16
17 prob+=lpSum(col_data[j])<=col_con[j]
TypeError: 'zip' object is not subscriptable
Your code breaks in this line:
col_data.append(list(zip(*dec_var)[j]))
Lets go through it step by step:
dec_var is an array, probably with multiple dimensions. Something like this:
dec_var=np.array([[1,2,3,4],[5,6,7,8]])
dec_var
#array([[1, 2, 3, 4],
# [5, 6, 7, 8]])
The star operator (*) breaks the array into 'variables'. Something more or less like this:
a = [1,2,3,4], b = [5,6,7,8].
('a' and 'b' don't really exist, just trying to paint a picture).
Next, you apply zip(), which allows you to iterate two iterables together. You would usually use it like this:
for i,j in zip([1,2],[3,4]):
print(i,j)
#1,3
#2,4
However, zip itself is not subscriptable, that is the error you are getting.
To make it subscriptable, you can apply list on it.
list(zip([1,2],[3,4]))[0]
#(1,3)
In other words.. The solution to your problem most likely is changing the position of the [j] subscript:
From:
col_data.append(list(zip(*dec_var)[j]))
To:
col_data.append(list(zip(*dec_var))[j])

Copy portion of list

How do I copy only a portion of a list to another list. For example, if the length of the list is 105 but only 30 of the randomly selected elements need to be copied to a new list.
This is the code that I have written
for x in range (104):
if len(trainingSet1)>30:
break
trainingSet1[x]= (trainingSet[random.randint(1,103)])
But it keeps giving this error:
Traceback (most recent call last):
File "Q1_2.py", line 82, in <module>
main()
File "Q1_2.py", line 72, in main
trainingSet1[x]= (trainingSet[random.randint(1,103)])
IndexError: list index out of range
The bug is probably here:
trainingSet1[x] = ...
Unless you already populated trainingSet1, you’re trying to assign to
an element that doesn’t exist yet. Use trainingSet1.append(...)
instead.
Initialize the trainingSet1 as trainingSet1 =[] and then try to append values to that instead of using trainingSet1[x] = value . If you really want to assign as you have done in the code you can first initialize the array as trainingSet1 = [0] * 30. This will assign 30 0's to the list and those will be replaced by your randomly selected values later.

understanding for loops and multidimensional arrays

as a hobby project I'm trying to make a grid of public available route listeners on the internet, for this, i'm logging into all of them and asking them them who they know and who is directly connected to them. which works fine, now i'm trying to pair them.
the math is pretty simple, if the last octet in the IP address is an even number, it's partner must be the next odd number and vice versa (some exceptions but i do those manually)
Now if you run the script here, you won't get any results, I did this on purpose to illustrate a problem i'm not sure how i reverse-problem-solve on.
Run this and i will get no errors, but if I add another element into the list
['ROUTER5124-A', '100.127.126.16', 'te0/0/24']
I get this error:
Traceback (most recent call last):
File "zac.py", line 38, in <module>
linknetsloop.remove(sublist)
ValueError: list.remove(x): x not in list
if I print out what inside linknetsloop.remove(sublist) and
linknetsloop.remove(items) It want's to delete the extra element i added, twice in fact. which is weird since it's partner .17 is not even there. I think the error is me looping through the list wrong, but I can't find my error after a few hours of searching.
#!/usr/bin/python3.5
import re
import ipaddress
linknets = [
['ROUTER1190-A', '100.127.126.81', 'te0/0/2'] ,
['ROUTER1190-A', '100.127.126.83', 'te0/0/3'] ,
['ROUTER1323-A', '100.127.126.125', 'te0/0/24'] ,
['ROUTER1323-A', '100.127.126.97', 'te0/0/25'] ,
['ROUTER1242-B', '100.127.126.173', 'te0/0/25'] ,
['ROUTER1190-B', '100.127.126.55', 'te0/0/24'] ,
['ROUTER1190-B', '100.127.126.57', 'te0/0/25'] ,
['ROUTER1190-C', '100.127.126.171', 'te0/0/24'] ,
['ROUTER1190-C', '100.127.126.59', 'te0/0/25'] ,
['ROUTER5345-A', '100.127.126.25', 'te1/0/12'] ,
['ROUTER5345-A', '100.127.126.47', 'te2/0/12'] ,
['ROUTER1610-A', '100.127.126.69', 'te0/0/24'] ,
['ROUTERP-1242', '100.127.126.85', 'eth1/1/3'] ,
['ROUTERP-1242', '100.127.126.63', 'eth1/1/4'] ,
['ROUTERP-1242', '100.127.126.104', 'eth1/2/1'] ,
]
linknetsloop = linknets
linknets_complete = []
for sublist in linknets:
search = 0
lastoctet = re.match('.*?([0-9]+)$', sublist[1]).group(1)
if int(lastoctet)%2==0: #Last octet is even
search = ipaddress.IPv4Address(sublist[1]) + 1
else:
search = ipaddress.IPv4Address(sublist[1]) - 1
for items in linknets:
if str(search) in items[1]:
print(sublist)
linknetsloop.remove(sublist)
linknetsloop.remove(items)
any pointers will be gladly appreciated
Most probably you wanted to copy the content of linknets:
linknetsloop = list(linknets)
Your original code does not copy the list, but merely creates alias to the same list. And then you are iterating on it, and changing its content while iterating, which will lead to unexpected results.
Then, you do a double loop on linknests and double deletion:
for sublist in linknets:
....
for items in linknets:
if <condition>:
linknetsloop.remove(sublist)
linknetsloop.remove(items)
This will raise ValueError exception when sublist==items and the item with that value exist only once. So you have to consider this situation.
Also, probably you have a bug in :
if str(search) in items[1]:
You are not comparing strings, but matching it. So if your search is '10.127.126.16' it will match to '210.127.126.168', for example.

Optimization of code to avoid occasional error "ValueError: need more than 0 values to unpack"

I have a program where it connects to a remote system (running Linux) using a telnet connection and runs a binary, which prints some values. I use read_very_eager() to retrieve those values to a buffer and process them (calculate the average of the values basically). The following is my code :
import telnetlib
import time
import string
lpr=[]
lpr_s=[]
lpr_val=[]
lpr_agg=[]
lpr_sum=0
tn1 = telnetlib.Telnet("192.168.1.101")
print tn1.read_until("login: ")
print tn1.write("root1\n")
time.sleep(1)
print tn1.read_until("Password:")
print tn1.write("\n")
print tn1.write("\n")
print tn1.read_until("root1#dvf99:~$")
print tn1.write("su\n")
print tn1.read_until("root#dvf99:/home/root1")
print tn1.write("\n")
time.sleep(10)
print tn1.write("<binary_name>\n")
time.sleep(5)
buf=tn1.read_very_eager()
print buf
time.sleep(10)
buf=tn1.read_very_eager()
print buf
lpr=buf.splitlines()[:10]
print "splitlines :\n"+str(lpr)
for line in lpr:
lpr_s.append([int(s) for s in line.split() if s.isdigit()])
print(lpr_s)
lpr_val,lpr_agg=zip(*lpr_s)
print(lpr_val)
print "\n"
print(lpr_agg)
for i in range(0,10):
lpr_sum+=lpr_val[i]
print(lpr_sum)
looper=lpr_sum/10
print "\nlooper="+str(looper)+"\n"
tn1.close()
Most of the times, I get output of the statement print(lpr_s) like :
[[46129, 461537], [46168, 507705], [46141, 553846], [46162, 600008], [46159, 646167], [46154, 692321], [46167, 738488], [46176, 784664], [46166, 830830], [46180, 877010]]
But some other times, I get output of the statement print(lpr_s) like :
[[], [46168, 1892467], [46157, 1938624], [46161, 1984785], [46178, 2030963], [46162, 2077125], [46166, 2123291], [46141, 2169432], [46172, 2215604], [46167, 2261771]]
Because of which I get the error ValueError: need more than 0 values to unpack at lpr_val,lpr_agg=zip(*lpr_s). Now, the challenge is I need to optimize the code with the constraint that the procedure should be the same - sleep for 5 seconds, leave the initial values, sleep for 10 seconds, collect 10 values and take their average. I suspect it is read_very_eager() the culprit here which causes the list being blank.
So, my questions are :
Should I consider replacing read_very_eager() with a better solution that I'm not aware of yet?
Should I just let read_very_eager() be and do something like checking for null values in the list and copy only the non-null values to another list? In this case I'm dealing with nested list (lists within a list). How do I get this done?
Why not just skip empty entries?
for line in lpr:
res = [int(s) for s in line.split() if s.isdigit()]
if res:
lpr_s.append(res)
or if the line turns out empty (I suppose this is it):
for line in lpr:
if not line:
continue
lpr_s.append([int(s) for s in line.split() if s.isdigit()])
You could run your list lpr_s through filter first to remove the empty lists from it:
lpr_s = filter(None, lpr_s)
(Note that the None specifies that filter should remove all the "falsey" values, which includes empty lists)

Categories