Hy!
As a complete beginner to python I wonder how I fetch a tuple-element inside a tuple of tuples - i.e. the result of
results=cursor.fetchall()
gives a tuple
((row1_value1,row1_value2,...),(row2_value1,row2_value2..),)
I know that
for id in results:
print id
or
results [i]
accesses each row as a whole.
But how do I directly access a tuple - value inside the tuple, i.e. row2_value3 ???
I helped myself with the following code, but isnĀ“t there a possibility to give a exact "adress", such as
results [i,sub-i] ??
for id in results:
a=results[i]
i=0
for x in a:
print a[i]
i+=1
I want to use fetchall, just to learn how to do things in python- i want to have the whole datbase in python and work with that.
Thanks a lot!
results[0][1]
accesses the second (1) element from the first (0) row (row1_value2 in your case). The lists in Python are 0-indexed.
The same way, row2_value3 is results[1][2]
You can just do results[row][field].
Related
I have two lists with just one element as follows(each of these two lists always contains only one element):
Vnew = [600]
Newoints2 = [(2447,3480)]
I'm trying to bring both of them together using the following code sample:
for i, key in enumerate(Vnew2):
pos3[key] = newpoints2[i]
But this returns an error as IndexError: list assignment index out of range
I actually did this one for other lists which have more than one element. It worked fine and got the output as {0:(1245,674),1:(2457,895),...}
Can someone find the mistake here?
It looks like you are trying to concatenate the lists into a new list. You don't always need to enumerate through the list.
You will be able to do this by Vnew + Newoints2
I am quite new to Python. I have a list containing some more lists, but only in two dimension (e.g. List[a][b]). Now for every value [a] I want to access a certain value [b] (10 in this case). For now it would be sufficent to just print every value List[a][10]. I tried:
for rec in List:
print List[rec][10]
That gives me the error "TypeError: list indices must be integers, not list". However if I just try "print List[0][10]" it gives me the value I want. In my for-Loop isn't rec an integer? How could I solve this problem?
Additional info: I am using Python 2.4.3 to be able to use the shapefile library that lets me access GIS data (my list).
for rec in List:
print rec[10]
should work.
You need to use:
for rec in List:
print rec[10]
or
for i range(len(List)):
print List[i][10]
rec in your case is not an integer, it is the first item of list. For you to use it as an integer you must add range in the for loop, like "for rec in range(0,len(List))"
Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple If ... Else statement. I tried to use %s string formatting but it won't work. Below code, so it will become more clear what I try to do:
if condition:
item = my_list['%s']
else:
item = my_other_list['%s']
# now I do something with this value:
print item % 3
This way I tried to print 3rd value of one or other list if the condition was True of False. This returned an error about list indices being string. So I tried to put it inside int() what didn't help.
How should I do it? The problem is I get the value later than I declare what item is.
EDIT
I will add some more infos here:
I have a for loop, that goes through ~1000 elements and processes them. If the condition is True, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements.
More code:
if self.dlg.comboBox_3.currentIndex == 0:
item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2)))
else:
item = QCustomTableWidgetItem(str(round(sum(values['%s'],2))))
for row in range(len(groups)):
group = QTableWidgetItem(str(groups[row]))
qTable.setItem(row,0,group)
qTable.setItem(row,1,item % row)
This is the actual code. Not the '%s' and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.
You have a reasonably large misconception about how list slicing works. It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string "%s", which can't possibly work.
There is no need to do this. You can just assign the list as the output from the if statement, and then slice that directly:
if condition:
list_to_slice = my_list
else:
list_to_slice = my_other_list
# now I do something with this value:
print list_to_slice[3]
Short answer:
'%s' is a string by definition, while a list index should be an integer by definition.
Use int(string) if you are sure the string can be an integer (if not, it will raise a ValueError)
A list is made up of multiple data values that are referenced by an indice.
So if i defined my list like so :
my_list = [apples, orange, peaches]
If I want to reference something in the list I do it like this
print(my_list[0])
The expected output for this line of code would be "apples".
To actually add something new to a list you need to use an inbuilt method of the list object, which looks something like this :
my_list.append("foo")
The new list would then look like this
[apples, orange, peaches, foo]
I hope this helps.
I'd suggest wrapping around a function like this:
def get_item(index, list1, list2)
if condition:
return list1[index]
else:
return list2[index]
print get_item(3)
Here is a compact way to do it:
source = my_list if condition else my_other_list
print(source[2])
This binds a variable source to either my_list or my_other_list depending on the condition. Then the 3rd element of the selected list is accessed using an integer index. This method has the advantage that source is still bound to the list should you need to access other elements in the list.
Another way, similar to yours, is to get the element directly:
index = 2
if condition:
item = my_list[index]
else:
item = my_other_list[index]
print(item)
Im pretty new to Python.
I have a list which looks like the following:
list = [('foo,bar,bash',)]
I grabbed it from and sql table (someone created the most rubbish sql table!), and I cant adjust it. This is literally the only format I can pull it in. I need to chop it up. I can't split it by index:
print list[0]
because that just literally gives me:
[('foo,bar,bash',)]
How can I split this up? I want to split it up and write it into another list.
Thank you.
list = [('foo,bar,bash',)] is a list which contains a tuple with 1 element. You should also use a different variable name instead of list because list is a python built in.
You can split that one element using split:
lst = [('foo,bar,bash',)]
print lst[0][0].split(',')
Output:
['foo', 'bar', 'bash']
If the tuple contains more than one element, you can loop through it:
lst = [('foo,bar,bash','1,2,3')]
for i in lst[0]:
print i.split(',')
this is a quick one. Suppose I got a multidimensional list of class objects, named table, and I need to access the class attribute .name.
I don't want to use nested loops, and of course to print this, I need to use format().
for i in range(3):
print '{0} - {1} - {2}'.format(*table[i].name)
Obviously that didn't work. As well as (*table[i]).name. I need to be able to access .name for each class object in the table[i] list. Mind if you put me to the right direction? Thanks in advance.
{arg_name.attribute_name} also works:
for row in table:
print(' - '.join('{0.name}'.format(elt) for elt in row))
Like this, for example:
for row in table:
print '{0} - {1} - {2}'.format(*[x.name for x in row])
I don't want to use nested loops
This is silly. To iterate over each element of a multidimensional array, you need to use nested loops. They may be implicit (map or a list comprehension) but that doesn't mean they're not there! The following is going to be much neater and cleaner than anything with map or a nasty format unpacking.
for row in table:
for elt in row:
print <...>
If you really want to know how to use your method:
import operator
for row in table:
print '{0} - {1} - {2}'.format(*map(operator.attrgetter('name'), row))
Tell me that's not messy and unclear compared to the above, not to mention the fact that you've hardcoded in the magic constant 3 -- what if you want to change to a 4x4 table?