all:
I want to create a string array and then pass it to a class in python as following:
from plottert import plotter
at[0]='./Re100/17/0.001/R/Vx-H'
at[1]='./Re100/33/0.001/R/Vx-H'
at[2]='./Re100/65/0.001/R/Vx-H'
b[0]='./U-0.001-H'
plotter (at,b)
but I got an error showing name 'at' is not defined.
I know that at.append() will do work. But, what I really want is to add the value to a SPECIFIC index of the array I want. Any help?
You could simply fill it with empty strings if you want
at = [''] * n #n = length of list
at[0]='./Re100/17/0.001/R/Vx-H'
at[1]=...
However as others have mentioned, you never initialized your list in the first place.
If you want to assign to indexes without having to know the final size of your data structure, use a dictionary instead:
at = {}
at[0] = 'zero'
at[4] = 'four' # look, it's sparse
As you can see, this also has the advantage (over append) that you can assign in any order.
If you want to convert this to an array later, you can do something like this:
at_arr = [at[i] if i in at else None
for i in range(max(at.keys())+1)]
# at_arr now holds the array ['zero', None, None, None, 'four']
First, create the lists (there is no non-basic-type arrays):
at = [''] * n # n = size of at
b = [''] * m # m = size of b
then execute your code.
You cant use lists you havent defined.
Related
First I tried directly storing values from a list having the name 'data' in an array variable 'c' using loop but 'none' got printed
for i in data:
print(i['name'])
c=i['name']
Here print(i['name']) perfectly worked and output appeared
This is the working ouput
Then I printed c in order to print the values generated using loop. The ouput came as none.
print(c)
Then I tried another way by storing the values and making the array iterable at the same time using for loop. An error occurred which I was unable to resolve.
for i in data:
b[c]=i['name']
c=c+1
The error apeared is as follow-
I have tried two ways, if there is any other way please help me out as I am new to python.
It looks like the variable 'data' is a dictionary.
If you want to add each name from that dictionary to a list:
# create a new list variable
names = []
for i in data:
name = i['name']
print(name)
# add the name to the list
names.append(name)
# output the new list
print(names)
Assuming your data object here is a list like [{"name": "Mr. Green", ...}, {"name": "Mr. Blue", ...}].
If your goal is to end up with c == ["Mr. Green", "Mr. Blue"], then you're looking for something like:
c = []
for i in data:
c.append(i['name'])
print(c)
or you can accomplish tasks like these using list comprehensions like:
c = [i['name'] for i in data]
print(c)
The first code example you posted is iterating through the items in data and reassigning the value of c to each item's name key - not adding them to a list("array"). Without knowing more about the code you ran to produce the screenshot and/or the contents of data, it's hard to say why you're seeing print(c) produce None. I'd guess the last item in data is something like {"name": None, ...} which if it's coming from JSON is possible if the value is null. Small note: I'd generally use .get("name") here instead so that your program doesn't blow up if an item is missing a "name" key entirely.
For your second code example, the error is different but I think falls along a similar logical fallacy which is that lists in python function differently from primitives(things like numbers and strings). For the interpreter to know that b or c are supposed to be lists("arrays"), they need to be instantiated differently and they have their own set of syntax/methods for mutation. For example, like arrays in other languages, lists are indexed by position so doing b[c] = <something> will only work if c is an integer. So something similar to your second example that would also produce a list of names like my above would be:
b = [None] * len(data)
c = 0
for i in data:
b[c]=i['name']
c=c+1
Note that if you only initialize b = [], you get an IndexError: list assignment index out of range on the initial assignment of b[0] = "some name" because the list is of size 0.
Add
b = []
above your first line of code. As the error is saying that you have not (and correctly so) defined the list to append.
I personally would use list comprehension here
b = [obj['name'] for obj in data]
where obj is i as you have defined it.
I have the following set in python (its actually one set item):
product_set = {'Product, Product_Source_System, Product_Number'}
I want to add a static prefix (source.) to all the comma seperated values in the set, so I get the following output:
{'source.Product, source.Product_Source_System, source.Product_Number'}
I tried with a set comprehension, but it doesn't do the trick or I'm doing something wrong. It only prefixes the first value in the set.
{"source." + x for x in set}
I know sets are immutable. I don't need a new set, just output the new values.
Anyone that can help?
Thanks in advance
Edit: Splitting the initial long string into a list of short strings and then (only if required) making a set out of the list:
s1 = set('Product, Product_Source_System, Product_Number'.split(', '))
Constructing a new set:
s1 = {'Product', 'Product_Source_System', 'Product_Number'}
s2 = {"source." + x for x in s1}
Only printing the new strings:
for x in s1:
print("source." + x)
Note: The shown desired result is a new set with updated comma-seperated values. Further down you mentioned: "I don't need a new set, just output the new values". Which one is it? Below an option to mimic your desired result:
import re
set = {'Product, Product_Source_System, Product_Number'}
set = {re.sub(r'^|(,\s*)', r'\1source.', list(set)[0])}
# set = {'source.'+ list(set)[0].replace(', ', ', source.')}
print(set)
Prints:
{'source.Product, source.Product_Source_System, source.Product_Number'}
I have a problem with my code, I just want to write the result in csv and i got IndexError
seleksi = []
p = FeatureSelection(fiturs, docs)
seleksi[0] = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(selections)
In p.select is:
['A',1]
['B',2]
['C',3]
etc
and i got error in:
seleksi[0] = p.select()
IndexError: list assignment index out of range
Process finished with exit code 1
what should i do?
[], calls __get(index) in background. when you say seleksi[0], you are trying to get value at index 0 of seleksi, which is an empty list.
You should just do:
seleksi = p.select()
When you initlialize a list using
seleksi = []
It is an empty list. The lenght of list is 0.
Hence
seleksi[0]
gives an error.
You need to append to the list for it to get values, something like
seleksi.append(p.select())
If you still want to assign it based on index, initialize it as array of zeros or some dummy value
seleksi = [0]* n
See this: List of zeros in python
You are accesing before assignment on seleksi[0] = p.select(), this should solve it:
seleksi.append(p.select())
Since you are iterating over saleksi I guess that what you really want is to store p.select(), you may want to do seleksi = p.select() instead then.
EDIT:
i got this selections.writerow(selections) _csv.Error: sequence
expected
you want to write x, so selections.writerow(x) is the way to go.
Your final code would look like this:
p = FeatureSelection(fiturs, docs)
seleksi = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(x)
import imgcompare
...
for filename in os.listdir(myPath):
if filename.endswith(".png"):
listIm1.append(filename)
for filename2 in os.listdir(myPath2):
if filename2.endswith(".png"):
listIm2.append(filename2)
so i fill my two lists with images,now I would like to compare the images of the two lists one by one following the same index, for example:listIm1[0] with listImg2[0]listIm1[1] with listImg2[1]and so on... and that's the code:
for item in listIm1:
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
print ifSame
but get the error:
same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2)
TypeError: list indices must be integers, not str
it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it
works?
since
if filename2.endswith(".png"):
listIm2.append(filename2)
for item in listIm1:
# item = "someimagine.png"
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
#listIm1[someimagine.png] is what you are asking => retrun Type Error
I guess you are looking for something like this:
edit:
import os
for filename in os.listdir(myPath):
if filename2.endswith(".png"):
img_path = os.path.join(myPath,filename2)
listIm2.append(img_path)
listIm1 = []
listIm2 = []
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
print ifSame
and it's better if len(listIm1) == len(listIm2)
The problem here is that you are trying to get the index of listIm1 by using item. What you want to do is use a range(), like:
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
As #Matt pointed out, this will only work if you know the lists are the same length beforehand, otherwise it will throw an index error.
You are using a for each loop, which grabs each element in your provided list listIm1 and stores it in a temp variable item, you then pass item (which is a string) as an index both of your lists. Indices of a list must be an integer, and that is the error you are getting.
for dir1_file in listIm1:
for dir2_file in listIm2:
ifSame = imgcompare.is_equal(dir1_file,dir2_file,tolerance=2)
print ifSame
This code uses two for each loops, it looks at each element in both of the lists and uses them as the arguments for your method.
i ran into a little logic problem and trying to figure it out.
my case is as follows:
i have a list of items each item represents a Group
i need to create a set of nested groups,
so, for example:
myGroups = ["head", "neck", "arms", "legs"]
i need to get them to be represented like this:
(if you can imaging a folder structure)
head
|_> neck
|_> arms
|_>legs
and so on until i hit the last element.
what i thought would work (but don't know really how to advance here) is:
def createVNTgroups(self, groupsData):
for i in range(len(groupsData)):
print groupsData[i]
for q in range(1, len(groupsData)):
print groupsData[q]
but in this case, i am running over same elements in 'i' that i already took with 'q'.
could someone give me a hint?
thanks in advance!
If I understood well, you want a nested structure. For this case, you can use a recursive function:
myGroups = ["head", "neck", "arms", "legs"]
def createVNTgroups(alist):
temp = alist[:] # needed because lists are mutable
first = [temp.pop(0)] # extract first element from list
if temp: # if the list still contains more items,
second = [createVNTgroups(temp)] # do it recursively
return first + second # returning the second object attached to the first.
else: # Otherwise,
return first # return the last element
print createVNTgroups(myGroups)
this produces a nested list:
['head', ['neck', ['arms', ['legs']]]]
Is that what you were looking for?
>>> m
['head', 'neck', 'arms', 'legs']
>>> reduce(lambda x,y:[x,y][::-1] if x!=y else [x], m[::-1],m[-1])
['head', ['neck', ['arms', ['legs']]]]