Python - get elements from list - python

From a python function, I get the following output:
['(0.412169, mississippi)']
The type indicates that it is a list. I want to extract the values from the list and save it as separate elements. I tried various functions to convert list to tuple, list to str, extracting the element by Index from the tuple or str, nothing worked out. When I try to extract the element by index, I either get '(' for the first element index 0, or when I try to extract through a iterator function, I get all the values split up like the full data set as a string.
How do I get values separately.

You can iterate over your data, remove the parentheses using slicing and split the string by comma to create a list, which will be appended to your output payload:
data = ['(0.412169, mississippi)', '(0.412180, NY)']
extracted_values = []
for d in data:
extracted_values += d[1:-1].split(",")
print(extracted_values)
# output: ['0.412169', ' mississippi', '0.412180', ' NY']

Your list content a string, not a list.
If you want to extract the content of a string, use the "eval" statement
my_tuple = eval("(0.412169, 'mississippi')")
Note that the "eval" function can be dangerous, because if your string content python code, it could be executed.

Related

string indices must be integers json

i have a json data https://steamcommunity.com/id/RednelssGames/inventory/json/730/2
need get names of all the items
r = requests.get('https://steamcommunity.com/id/RednelssGames/inventory/json/730/2')
if r.json()['success'] == True:
for rows in r.json()['rgDescriptions']:
print(rows['market_hash_name'])
getting error string indices must be integers
Change the for-loop as follows:
for rows in r.json()['rgDescriptions'].values():
print(rows['market_hash_name'])
By iterating over a dictionary like you did, you get the keys and not the values (rows). If you want to iterate over the values, you have to iterate over the return value of dict.values().
From the link you provided:
"rgDescriptions":{"4291220570_302028390":
rgDescriptions doesn't return an array, but an object (a dictionary, in this case) (notice the opening curly brace ({) rather than a regular square brace ([)).
By using for rows in r.json()['rgDescriptions']: you end up iterating over the dictionary's keys. The first key of the dictionary seems to be "4291220570_302028390", which is a string.
so when you do print(rows['market_hash_name']), you're attempting to access the 'market_hash_name' "index" of your rows object, but rows is actually a string, so it doesn't work.

Pymongo find using $in with a list

The folowing expression works fine, returning the values that match the values list:
[...].find({"FieldName":{"$in":["Value1", "Value2", "Value3"]}})
But i have the list of values in a list object, like this:
valuesList = list()
valuesList.append("Value1")
valuesList.append("Value2")
valuesList.append("Value3")
But using the list object, a get no results:
[...].find({"FieldName":{"$in":[valuesList]}})
I Have also tried expanding the list in a formated string, like this:
strList = ', '.join(valuesList)
[...].find({"FieldName":{"$in":[strList]}})
but also, no results.
Note: If i force the list to have only one value, it works. Only when multiple values are suplied, the result is blank.
Any ideas on how to use "$in" in pymongo with a list of values in a list object?
I believe your problem is the fact that you have a list inside of a list.
Instead of:
[...].find({"FieldName":{"$in":[valuesList]}})
Try:
[...].find({"FieldName":{"$in":valuesList}})

Outputting None instead of Values

I am trying to utilize list comprehension to populate a new list, which is the length of text in a DataFrame column.
So if the text is "electrical engineer", it should output 19 etc. Instead, it just fills the list with None values
I have written out list comprehension below
all_text_length = [all_text_length.append(len(i)) for i in data['all_text']]
Expecting output of integer but its None
As a workaround, I am currently using (successfully)
[all_text_length.append(len(i)) for i in data['all_text']]```
Read the documentation on append: it works in-place. There is no returned value. What you've written is essentially
all_text_length = [None for i in data['all_text']]
It appears that you're trying to make a list comprehension to entirely change your list. Try this:
all_text_length = [len(i) for i in data['all_text']]
If you just need the lengths in a convenient form, would it do to form a new column? Simply apply len to the df column.
The value before the "for" statement in the list comprehension, will be added to the list. If you place a statement in there, like
all_text_length.append(len(i)
, the return value of that function will be added. Because .append() doesnt have areturn-statement in it, you get the value None as return type, wich will be added to your list.
Use the code #Prune recommended and it should work as you want.
You are trying to append to the same list on which you are doing list comprehension. Since the append returns a None type, you are getting None. The below code should work,
all_text_length = map(len, data['all_text'])
map is a function that takes another function (first argument) and applies it to every element in an iterable (second argument) and returns a list of the results.

Using pop on a list containing a string

I have a list:
listA = ['1,2,3,4,5']
where it is in string format. I want to perform a simple function that removes the last digit in the string, which in this case would be 5 and print it out.
I've tried something
listA = ['1,2,3,4,5']
for i in listA:
print(listA.pop())
What i tried is wrong as I'm not familiar with using pop on strings.
What you have is not a list of integers. It is a list with a single element, that element is a string of comma separated integers
You're not using i
You're iterating over the list and mutating it as you do so. Do not do this, because it does not give you the behaviour you expect.
I would recommend a while loop instead. First, fix your array.
listA = listA[0].split(',')
Now, iterate over it.
while listA:
print(listA.pop())
You use the truthiness of a nonempty list to keep iterating over it. This removes all the digits. However, if you just want the last digit and nothing more, call listA.pop() only once.
If you don't want to fix your array, you should extract the last digit like this:
listA = ['1,2,3,4,5']
print(int(listA[0][-1])) # [0] gets the string, [-1] gets the last character in the string
This is ungainly, so I recommend fixing your array instead.
The previous answer is giving you the last character. You can also extract the last value using split which will break up text based on a defined delimiter:
listA = ['1,2,3,4,5']
print( listA[0].split(',')[-1] )

Splitting up a list with all values sitting in the same index in Python

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(',')

Categories

Resources