Contain Output in a List - python

For my below code everything is working correctly, however I am trying to store my output in a list and I can't figure out how to do so. I tried to create an empty list and append the output to that list but it did not work. Any help would be great!
sample_photo_rep["photo"]["tags"]["tag"]
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
print [sample_tags_list['raw'].decode('utf-8')]
current output:
[u'Nature']
[u'Mist']
[u'Mountain']
correct output: [u'nature', u'mist', u'mountain']

In each loop, you're printing a list containing a single element, i.e. [u'Nature'], [u'Mountain'], etc.
If you remove the enclosing braces, i.e. [sample_tags_list['raw'].decode('utf-8')] to sample_tags_list['raw'].decode('utf-8'), you should just get the string.
Not sure why your append didn't work, as
output = []
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
output.append(sample_tags_list['raw'].decode('utf-8'))
should do the trick. A list comprehension would accomplish the same thing as in the answer from #abccd; both give the same output.

declare an empty list at the top of your code like this:
tags = []
Then, instead of printing it out in your for loop append it to the list:
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
tags.append([sample_tags_list['raw'].decode('utf-8')])
Then tags should be this:
[u'nature', u'mist', u'mountain']
Further Reading
Info on appending to lists: https://www.tutorialspoint.com/python/list_append.htm
Info on lists in general:
https://developers.google.com/edu/python/lists

You can always use list comprehension like this:
print [sample_tags_list['raw'].decode('utf-8') for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]]
In place of your for loop. This is by far still the most preferred way of doing this. You can see the pydoc for a simple example of using list comps.

Related

How to iterate over a list while applying a regex to it in Python?

I'm trying to run this block of code.
castResultType = list(filterResultSet[1:32:5])
cleanList = []
for i in castResultType:
cleanList.append(re.sub('[^\d\.]', '',castResultType[i]))
print(cleanList)
I'm hoping to get essentially each item in the list castResultType, which is getting specific values from the list filterResultSet inserted into the empty list cleanList. While also having the regex above applied to each value from castResultType before it's inserted into cleanList. I'm sure I'm doing something wrong, and would appreciate any assistance. I'm also very new to python and programming in general, so I apologize if I'm asking something stupid.
The problem you're (probably) facing is in this line: for i in castResultType.
What this line is doing is looping over the values within our (list) castResultType and assigning its elements to i. However, when you call castResultType[i], you're asking for a non-existent index of the list.
What you probably meant to do is:
for i in range(len(castResultType)):
cleanList.append(re.sub('[^\d\.]', '',castResultType[i]))
# etc
What you could also do is:
for i in castResultType:
cleanList.append(re.sub('[^\d\.]', '', i))
# etc
There are a lot of other ways of coding what you want to do, but these are probably the most familiar for a beginner.
In addition to the bug in your looping, the problem could be in your use of regular expressions. I recommend experimenting with your regular expression on a single element from castResultType before looping through.
You can use the built-in map function to map a function to items in an iterable:
clean_list = list(map(lambda elem: re.sub('[^\d\.]', '', elem), castResultType))

List append in a "for" loop

I am trying to get a list of elements using a for loop to index my previous list. Here's the code:
for index in range(1,810):
list.extend(t[index])
list.extend(t[index+1])
list.extend(t[index])
I already have a list named "list" and t is an other list.
To be more specific I want to make my list like this.
t1,t2,t1,t2,t3,t2,t3,t4 etc.
I get this error TypeError: 'float' object is not iterable.
You should be using list.append since list.extend works on iterables; i.e. you can do stuff like lst=[1,2,3];lst.extend([4,5]) which would give you [1,2,3,4,5]
see this link if you want to read more
The other answers suggesting you use append fix your issue, but appending is very inefficient. You should use a list comprehension. Also, "list" is a keyword, so you should use another name.
my_list = [item for index in range(1,810) for item in [t[index],t[index+1],t[index]] ]

Python list.remove items present in second list

I've searched around and most of the errors I see are when people are trying to iterate over a list and modify it at the same time. In my case, I am trying to take one list, and remove items from that list that are present in a second list.
import pymysql
schemaOnly = ["table1", "table2", "table6", "table9"]
db = pymysql.connect(my connection stuff)
tables = db.cursor()
tables.execute("SHOW TABLES")
tablesTuple = tables.fetchall()
tablesList = []
# I do this because there is no way to remove items from a tuple
# which is what I get back from tables.fetchall
for item in tablesTuple:
tablesList.append(item)
for schemaTable in schemaOnly:
tablesList.remove(schemaTable)
When I put various print statements in the code, everything looks like proper and like it is going to work. But when it gets to the actual tablesList.remove(schemaTable) I get the dreaded ValueError: list.remove(x): x not in list.
If there is a better way to do this I am open to ideas. It just seemed logical to me to iterate through the list and remove items.
Thanks in advance!
** Edit **
Everyone in the comments and the first answer is correct. The reason this is failing is because the conversion from a Tuple to a list is creating a very badly formatted list. Hence there is nothing that matches when trying to remove items in the next loop. The solution to this issue was to take the first item from each Tuple and put those into a list like so: tablesList = [x[0] for x in tablesTuple] . Once I did this the second loop worked and the table names were correctly removed.
Thanks for pointing me in the right direction!
I assume that fetchall returns tuples, one for each database row matched.
Now the problem is that the elements in tablesList are tuples, whereas schemaTable contains strings. Python does not consider these to be equal.
Thus when you attempt to call remove on tablesList with a string from schemaTable, Python cannot find any such value.
You need to inspect the values in tablesList and find a way convert them to a strings. I suspect it would be by simply taking the first element out of the tuple, but I do not have a mySQL database at hand so I cannot test that.
Regarding your question, if there is a better way to do this: Yes.
Instead of adding items to the list, and then removing them, you can append only the items that you want. For example:
for item in tablesTuple:
if item not in schemaOnly:
tablesList.append(item)
Also, schemaOnly can be written as a set, to improve search complexity from O(n) to O(1):
schemaOnly = {"table1", "table2", "table6", "table9"}
This will only be meaningful with big lists, but in my experience it's useful semantically.
And finally, you can write the whole thing in one list comprehension:
tablesList = [item for item in tablesTuple if item not in schemaOnly]
And if you don't need to keep repetitions (or if there aren't any in the first place), you can also do this:
tablesSet = set(tablesTuple) - schemaOnly
Which is also has the best big-O complexity of all these variations.

How to use list comprehension on this for loop in python

I've just learned of list comprehension but I can't quite get it to work in the right context.
my for loop is:
results and instances are lists
for i in results:
instances.remove(i)
results.remove(i)
I tried [i for i in one if one.count(i)<2 if two.count(i)<2] but it doesn't work. I can get it to work on just one of them with this, [i for i in one if one.count(i)<2], but I wanted to incorporate both of them into the same loop. Can someone show me the easiest way to go about this?
Assuming results is a list. You seem to be trying to do this
for i in results:
instances.remove(i)
del results[:]
list comprehension is the wrong thing to use here. You're not trying to create a new list from a sequence.
This loops is similar, but will remove the instances in the reverse order
while results:
instances.remove(results.pop())
You need to first take the results out of the for loop. Set it after it and then delete it once the for loop has finished.

Python inserting lists into a list with given length of the list

My problem is, that need a list with length of 6:
list=[[],[],[],[],[],[]]
Ok, that's not difficult. Next I'm going to insert integers into the list:
list=[[60],[47],[0],[47],[],[]]
Here comes the real problem: How can I now extend the lists and fill them again and so on, so that it looks something like that:
list=[[60,47,13],[47,13,8],[1,3,1],[13,8,5],[],[]]
I can't find a solution, because at the beginning i do not know the length of each list, I know, they are all the same, but I'm not able to say what length exactly they will have at the end, so I'm forced to add an element to each of these lists, but for some reason i can't.
Btw: This is not a homework, it's part of a private project :)
You don't. You use normal list operations to add elements.
L[0].append(47)
Don't use the name list for your variable it conflicts with the built-in function list()
my_list = [[],[],[],[],[],[]]
my_list[0].append(60)
my_list[1].append(47)
my_list[2].append(0)
my_list[3].append(47)
print my_list # prints [[60],[47],[0],[47],[],[]]

Categories