Creating a Tuple made of variable strings - python

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?

Related

PrettyTable for loop is telling me TypeError: PrettyTable.add_row() takes 2 positional arguments but 8 were given

I have been trying to figure out what the issue is and can't seem to figure it out.
valueRange = [j.value for i in copyRange for j in i]
vrCounter = 0
vrStep = 7
x.field_names = ["Jurisdiction","SPOC-Name", "Lines of Business","Market Area", "Consultant Personal Lines", "Consultant Business Lines", " ROC-Name"]
for i in range(0,len(valueRange)):
x.add_row(valueRange[i], valueRange[i+1], valueRange[i+2], valueRange[i+3], valueRange[i+4], valueRange[i+5], valueRange[i+6])
print(x)
I ran the code without the x.add_row() function and it printed the values correctly. The valueRange list is just a bunch of keywords that match the field_names.
As shown in the docs, add_row() takes a list of values as an argument.
Enclose all the values in a list and it must work.
x.add_row([valueRange[i], valueRange[i+1], valueRange[i+2], valueRange[i+3], valueRange[i+4], valueRange[i+5], valueRange[i+6]])
Turn out the issue was the for i in range(0,len(valueRange)): portion. So it wasn't possible to answer this question without complete information about that valueRange list. This list contained 28 (0-27) string values. The loop was stepping through the 0-27 range 1 at a time while trying to apply an i+number value to each one. This would quickly go out of bounds unless the step size matches the valueRange list.
The final solution looks like:
for i in range(0,len(valueRange),7):
x.add_row(valueRange[i:i+7])

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.

Writing multiple lists to the same .dat file simultaniously in Python 2.7?

This is my translation from pseudocode. The code suggests that multiple lists or arrays can be written to a .dat file. I'm trying to stay as true to the pseudocode format as I can so that I don't get lost in the Debugging process. For sake of space I have left out the actual Pseudocode. I know how to write everything into a .txt or .csv as string but is it possible to write them into the same file allowing each object to keep it's original value?(Num=Num and str=str)
#THIS IS THE PREMISE OF THE PSEUDOCODE
#Cooper College maintains a master file of students and credits
#earned. Each semester the master is updated with a transaction
#file that contains credits earned during the semester.
#Each file is sorted in Student ID number order.
THIS IS WHAT I'M ATTEMPTING TO TRANSLATE INTO PYTHON
#getReady()
# open master "studentFile.dat"
# open trans "semesterCredits.dat"
# open newMaster "updatedStudentFile.dat"
# readMaster()
# readTrans()
# checkBoth()
#return
#
#readMaster()
# input masterID, masterName, masterCredits from master
# if eof then
# masterID = HIGH_VALUE
# endif
#return
THIS IS WHAT I WAS TRYING TO USE TO CREATE A STARTER FILE
#EACH LIST HAS A RANGE OF [0, 4]
masterID =[100000,100001,100002,100003]
masterName =['Bevis, Ted','Finch, Harold','Einstein, Al','Queen, Liz']
masterCredits = [56,15,112,37]
master = open('studentFile.dat','wb')
master.write(masterID,masterName,masterCredits)
print master.readlines()
#THIS IS MY TRACEBACK ERROR
#Traceback (most recent call last):
# File "C:/Users/School/Desktop/Find the Bugs Ch7/debug07-03start.py",
#line 6, in <module>
#master.write(masterID,masterName,masterCredits)
#TypeError: function takes exactly 1 argument (3 given)
EXPECTED OUTPUT
print master.readlines()
[[100001,'Bevis, Ted',56],[100002,'Finch, Harold',15],[100003,'Einstein, Al',112]...]
You can get your desire lists with zip :
>>> zip(masterID,masterName,masterCredits)
[(100000, 'Bevis, Ted', 56), (100001, 'Finch, Harold', 15), (100002, 'Einstein, Al', 112), (100003, 'Queen, Liz', 37)]
Then all you need is looping over your zipped list and write to file :
with open('studentFile.dat','wb') as master:
for i,j,k,z in zip(masterID,masterName,masterCredits) :
master.write(','.join((str(i),j,k,str(z))))
write takes a string, and you are passing a bunch of object. These need to be converted to string before printing. One way of doing this is
master.write(','.join([masterID,masterName,masterCredits]))
You make a list out of the items, join them with a comma and write to file.

select and make new list with specific information

EDIT2: Nevermind this, someone pointed my error. Thanks
first of all, this is an example of results i have
(172, 'Nucleus')
(172, 'Nucleus')
(472, 'Cytoplasm')
(472, 'Cytoplasm')
(472, 'Nucleus')
what i`m trying to do is to match the first number (position 0) and then look if there is a part of the word "nucleus" (here, it would be "nuc") It can happens that in each number there is only word that has nucleus.
i'm trying to make 2 lists : the first list would be only the number containing only "nuc" word. the second list would be containing those with nuc and other things (like cytoplasm in my example)
That is only a little part of my result.
I don't have example of code, because i have really no clue how to include only one valor of my query in the list ( as on the example, i would enter the number 172 two time) (oops i now have an example of code)
EDIT: oops wrote that before i wrote the code i tried...
right now, my code looks like that :
here is how i got my example a little bit higher
def number1(self, position):
self.position = position
List = [self.name()]
for item in List:
for i in range(position, self.c.rowcount):
self.number(i)
def separate_list(self, list_signal):
nuc_list = []
not_nuc_list = []
for i in list_signal:
print(list_signal(i))
if list_signal(i)(0) == list_signal(i+1)(0):
if list_signal(i)(1) and list_signal(i+1)(1) == re.search("nuc"):
nuc_list.append(list_signal(i))
else:not_nuc_list.append(list_signal(i))
return nuc_list and not_nuc_list
dc = connection()
dc.separate_list(dc.number1(0))
error:
Traceback (most recent call last):
File "class vincent.py", line 91, in <module>
dc.separate_list(dc.number1(0))
File "class vincent.py", line 61, in separate_list
for i in list_signal:
TypeError: 'NoneType' object is not iterable
i know this is not cute, i tried doing it the best way i can .. (new to python and programming in itself)
EDIT2: Nevermind this, someone pointed my error. Thanks
A few things, if you are trying to get the index, position 0 of the list as you say, you would use list_name[0], if you are using position to sort, use a different method
Are (172, 'Nucleus') ... (172, 'Nucleus') tuples or are they lists of their own? List you can use index with the [0] method, tuple you can assign it to two variables to work with the data as number, cell_type = (172, 'nucleus')
Also, at the moment dc.number1 doesn't return anything so it cant be used at input to another function. Add a return of some sort or change what you are using as the input to whatever self.number is modifying.
You may want to make a list of all your results, e.g. [(172, 'Nucleus'), ...(172, 'Nucleus')] then you can iterate through with
for item in results_list:
for number, cell_type in item:
print str(number), cell_type
#Should give you "172 Nucleus"

Python Image Library: How to combine 4 images into a 2 x 2 grid?

I have 4 directories with images for an animation. I would like to take the set of images and generate a single image with the 4 images arranged into a 2x2 grid for each frame of the animation.
My code so far is:
import Image
fluid64 = "Fluid64_half_size/00"
fluid128 = "Fluid128_half_size/00"
fluid512 = "Fluid512_half_size/00"
fluid1024 = "Fluid1024_half_size/00"
out_image = "Fluid_all/00"
for pic in range(1, 26):
blank_image = Image.open("blank.jpg")
if pic < 10:
image_num = "0"+str(pic)
else:
image_num = str(pic)
image64 = Image.open(fluid64+image_num+".jpg")
image128 = Image.open(fluid128+image_num+".jpg")
image512 = Image.open(fluid512+image_num+".jpg")
image1024 = Image.open(fluid1024+image_num+".jpg")
out = out_image + image_num + ".jpg"
blank_image.paste(image64, (0,0)).paste(fluid128, (400,0)).paste(fluid512, (0,300)).paste(fluid1024, (400,300)).save(out)
Not sure why it's not working. I'm getting the error:
Traceback (most recent call last):
File "C:\Users\Casey\Desktop\Image_composite.py", line 24, in <module>
blank_image.paste(image64, (0,0)).paste(fluid128, (400,0)).paste(fluid512, (
ste(fluid1024, (400,300)).save(out)
AttributeError: 'NoneType' object has no attribute 'paste'
shell returned 1
Any help would be awesome. Thanks!
The only problem there is that "paste" does not return an image object - it rather modifies the "blank" image inplace.
So, when the second paste is called (the one that uses the fuild128 image), it tries to be applied on "None" - which is the return value of the first image.
If that is the only problem you are having, just make one paste call per line, like this:
blank_image.paste(image64, (0,0))
blank_image.paste(fluid128, (400,0))
blank_image.paste(fluid512, (0,300))
blank_image.paste(fluid1024, (400,300))
blank_image.save(out)
Although it looks likely you'd need to scale each image so that their format match as well.
And your code for the "image_num" variable is unecessary. Python is really good with strings - just do something like this:
image64 = Image.open(fluid64 + "%02d.jpg" % pic)
You may want to be using something along the lines of :
blank_image = Image.new("RGB", (800, 600))
This will create a new area in memory in which you can generate your image. You should then be able to paste you images into that.
Then you'll need to save it out again later on with:
blank_image.save("blank.jpg")
Read the error message:
AttributeError: 'NoneType' object has no attribute 'paste'
This means you tried to call .paste on something that was of type NoneType, i.e. on the None object.
Image.paste returns None. You can't "chain" together calls like that except when the functions are specifically designed to support it, and Image.paste is not. (Support for this sort of thing is accomplished by having the function return self. You get an error that talks about NoneType because the function is written not to return anything, and everything in Python returns None by default if nothing else is returned explicitly.) This is considered Pythonic: methods either return a new value, or modify self and return None. Thus, so-called "fluent interfaces" are not used when the functions have side effects - Pythonistas consider that harmful. Returning None is a warning that the function has side effects. :)
Just do four separate .paste calls.
Tiling figures in a 2-by-2 grid would be easy to achieve with the append_images function defined in this reply
https://stackoverflow.com/a/46623632/8738113
For example:
img1 = append_images([image64, image128], direction='horizontal')
img2 = append_images([image512, image1024], direction='horizontal')
final = append_images([img1, img2], direction='vertical')
final.save("Fluid_all/00.jpg")
Unlike PIL APIs copy, crop, resize or rotate which return an Image object, paste returns None which prevents chained method calls. Not so convenient API design.

Categories