Python 3: how to create list out of float numbers? - python

Anyone knows how can I solve this issue?
I have the following code.
result=[]
for i in range(len(response_i['objcontent'][0]['rowvalues'])):
lat = response_i['objcontent'][0]['rowvalues'][i][0]
print(lat)
for i in lat:
result.append(i)
print (result)
Following is the output of print(lat):
92.213725
191.586143
228.981615
240.353291
and following is the output of print(result):
['9', '2', '.', '2', '1', '3', '7', '2', '5', '1', '9', '1', '.', '5', '8',
'6', '1', '4', '3', '2', '2', '8', '.', '9', '8', '1', '6', '1', '5', '2',
'4', '0', '.', '3', '5', '3', '2', '9', '1']
I expected to get the output in following format:
[92.213725, 191.586143, 228.981615, 240.353291]
Anyone knows how to fix this issue?
Thanks

So, your error is that instead of simply adding your latitute to the list, you are iterating over each character of the latitude, as a string, and adding that character to a list.
result=[]
for value in response_i['objcontent'][0]['rowvalues']:
lat = value[0]
print(lat)
result.append(float(lat))
print (result)
Besides that, using range(len(...))) is the way things have to be done in almost all modern languages, because they either don't implement a "for ...each" or do it in an incomplete or faulty way.
In Python, since the beginning it is a given that whenever one wants a for iteration he wants to get the items of a sequence, not its indices (for posterior retrieval of the indices). Some auxiliar built-ins come in to play to ensure you just interate the sequence: zip to mix one or more sequences, and enumerate to yield the indices as well if you need them.

Related

Adding numbers to lists in Python but will add 1 and 0 instead of 10

Still in my quest for the Josephus problem, I ran across a small problem in the following code
(example code showing the problem without all the Josephus crap, exact same issue with both)
listy = []
var = 0
while var < 15:
var += 1
listy += str(var)
print("var: ", str(var))
print(listy)
print("")
print("")
print(listy)
Instead of adding, for example, 10 to the list, it will add 1 and 0. So instead of listy looking like:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
etc as it should, it looks like:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', '1', '1']
etc. So the full output of the above gave this:image
Any help?
Changing
listy += str(var)
to
listy.append(str(var))
fixes the problem

Creating Dictionary Value Based on Startswith

How can I separate lists into one dictionary based on whether it starts with an letter or number?
webscrape1= ['Owner1','Owner2', 'Owner3', '555 Address Street',]
webscrape2 = ['Owner1','555 Address Street',]
webscrape3 = ['Owner1','Owner2', 'Owner3', 'Owner4', 'Owner5', '555 Address Street',]
An attribute error occurs if I try:
address = address[1:].startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
This should give you the expected result:
d = {"Owner" : [], "Address" : []}
for el in webscrape:
if el.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')):
d["Address"].append(el)
else:
d["Owner"].append(el)
print(d)
I can see from the code that your list always contains the address at the last index of the list. So you can directly fetch that using the webscrape[-1] statement and to fetch all the owners simply index from the beginning to the second last element. webscrape[0:webscrape.length-1].

Is there a way to generate a list string within Python, without any other 3rd party packages?

this code generates a list of integers
dir_list = list(range(11))
dir_list
numpy could transfer each element to string type
import numpy as np
dir_list = np.array(dir_list, dtype=np.str)
dir_list
array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
dtype='<U2')
is there a way to finish the job within Python, without any other 3rd party packages?
You can simply map each integer to string using inbuilt map function and map returns iterator so you can convert it into list.
list(map(str, range(11))) should do.
output:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Of course, this way you can iterate over each element of range object and convert to str and store as list:
dir_list = [str(i) for i in range(11)]
>>> dir_list
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Python Findall not finding anything

I am learning about Regex and am stuck with this code:
import re
resume = '''
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
'''
phoneRegex = re.compile(r'\d')
mo = phoneRegex.findall(resume)
print(mo.group())
When I try with search instead of findall, it works. But it can't find any match with findall.
What am I doing wrong?
findall() returns a simple list of strings matching the pattern.
It has no group() method, just omit that:
>>> print(mo)
['7', '3', '8', '3', '8', '3', '5', '7', '2', '9', '3', '7', '3', '5', '7',
'7', '0', '4', '9', '2', '4', '0', '3', '4', '4', '3', '2', '7', '5', '9',
'3', '7', '5', '8', '8', '0', '8', '5', '7', '6', '6', '4', '1', '5', '7',
'6', '2', '3', '4', '2', '9', '5', '1', '2', '6', '8', '8', '7', '4', '4']
It seems that you're trying to match phone numbers in resume, for that you can use:
resume = '''
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
'''
mo = re.findall(r'\(\d{3}\) \d{3}-\d{4}', resume)
for x in mo:
print(x)
Output:
(738) 383-5729
(373) 577-0492
(403) 443-2759
(375) 880-8576
(641) 576-2342
(951) 268-8744
Python Demo
Regex Demo & Explanation
Since (it looks like) you're just out for the numbers, you could do something like
>>> [''.join(c for c in l if c in '0123456789') for l in resume.strip().splitlines()]
['7383835729', '3735770492', '4034432759', '3758808576', '6415762342', '9512688744']
That might save you some trouble from internationally formed numbers (such as +46-(0)7-08/123 456 and the like).
Re.findall() module is used when you want to iterate over the lines by line, it will return a list of all the matches not group.
So in your case it returns as list
print(mo[0])

Remove duplicate items from list

I tried following this post but, it doesnt seem to be working for me.
I tried this code:
for bresult in response.css(LIST_SELECTOR):
NAME_SELECTOR = 'h2 a ::attr(href)'
yield {
'name': bresult.css(NAME_SELECTOR).extract_first(),
}
b_result_list.append(bresult.css(NAME_SELECTOR).extract_first())
#set b_result_list to SET to remove dups, then change back to LIST
set(b_result_list)
list(set(b_result_list))
for brl in b_result_list:
print("brl: {}".format(brl))
This prints out:
brl: https://facebook.site.com/users/login
brl: https://facebook.site.com/users
brl: https://facebook.site.com/users/login
When I just need:
brl: https://facebook.site.com/users/login
brl: https://facebook.site.com/users
What am I doing wrong here?
Thank you!
you are discarding the result when you need to save it ... b_result_list never actually changes... so you are just iterating over the original list. instead save the result of the set operation
b_result_list = list(set(b_result_list))
(note that sets do not preserve order)
If you want to maintain order and uniqueify, you can do:
>>> li
['1', '1', '2', '2', '3', '3', '3', '3', '1', '1', '4', '5', '4', '6', '6']
>>> seen=set()
>>> [e for e in li if not (e in seen or seen.add(e))]
['1', '2', '3', '4', '5', '6']
Or, you can use the keys of an OrderedDict:
>>> from collections import OrderedDict
>>> OrderedDict([(k, None) for k in li]).keys()
['1', '2', '3', '4', '5', '6']
But a set alone may substantially change the order of the original list:
>>> list(set(li))
['1', '3', '2', '5', '4', '6']

Categories

Resources