How to convert list of strings into floats? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the list of data:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
I need to convert it into float in order to calculate the average and etc.
I've tried:
list(map(float, rfd_per_neihborhood_15))
list(np.float_(rfd_per_neihborhood_15))
for item in list:
float(item)
a = rfd_per_neihborhood_15
floats = []
for element in a:
floats.append(float(element))
print(floats)
Nothing is working, it's throwing ValueError: could not convert string to float: '-'

The problem could be that there is an element in your list which has a - (hyphen). To tackle that, you can use try-except in the following manner:
rfd_per_neihborhood_15 = ['75.8','108.5','76.6','96.4','104.8','95.8','165.8','128.9','4-4']
def safe_float(x):
try:
return float(x)
except:
print(f"Cannot convert {x}")
#Returning a 0 in case of an error. You can change this based on your usecase
return 0
list(map(safe_float, rfd_per_neihborhood_15))
Output:
Cannot convert 4-4
[75.8, 108.5, 76.6, 96.4, 104.8, 95.8, 165.8, 128.9, 0]
As you can see, my code gracefully handled the exception and returned a 0 in place of the last element '4-4'. Alternatively, you could also return a NaN.

You could try this:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
# shortening the name to r_pn15
r_pn15 = rfd_per_neihborhood_15
floated_list = []
for item in r_pn15:
r_pn15.append(float(item))
print(floated_list)

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)

Python create nested dict in for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to created a nested dictionary but I have a problem inside the for loop, at least is what I'm thinking.
I do several requests based on args passed but when I try to add values to the nested dict created before it just adds the last arg passed.
I'll show the code and the output.
def api_metrics():
my_list = []
my_dict_1 = {}
number = len(my_metrics)
metricz = range(number)
for indice in metricz:
my_dict_1[indice] = {}
for metric in my_metrics:
urlnotoken = ""
urlnotoken = urlnotoken.replace(" ","%20")
preurl = urlnotoken + "&dateToken="+expirationDate
msg = preurl + apikey
token = calcMd5(msg)
finalurl = "http://"+host+preurl+"&token="+token
data_get = requests.get(finalurl, headers=app_headers)
json_data = json.loads(data_get.text)
metrics_path = json_data['data'][0]['metrics'][0]
metric_name = metrics_path['label']
metric_value = metrics_path['values'][0]['data'][0][1]
metric_unit = metrics_path['magnitudes']['y']
my_list.append(metric_name)
my_list.append(metric_value)
my_list.append(metric_unit)
number = len(my_metrics)
metricz = range(number)
my_values = metric
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
return(my_dict_1)
And the output
{0: 'avgRenditionSwitchTime', 1: 'avgRenditionSwitchTime', 2: 'avgRenditionSwitchTime', 3: 'avgRenditionSwitchTime', 4: 'avgRenditionSwitchTime'}"
This should output the different args passed. I have moved the code inside and outside the loop, I've read lots of posts but I need further help!
Cheers.
In here:
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
You are assigning the value of metric to all your dict (my_dict_1) items. Reason why 'it just adds the last arg passed'.
Without cleaning up your code, here's the patch to fix your issue:
for i, metric in enumerate(my_metrics):
...
my_dict_1[i] = metric

Linking elements of a list as a tree [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.
You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child
Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

Error adding list in loop condition in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
while dir_loop_water < water_lenth:
ds_water = gdal.Open('path'+ dirlist_water[dir_loop_water] , gdal.GA_ReadOnly)
numer_of_band_water = str(ds_water.RasterCount)
if numer_of_band_water == '3':
print('water condition matched')
rb_water = ds_water.GetRasterBand(1)
band1_water_tmp = rb_water.ReadAsArray()
band1_water = band1_water_tmp.tolist()
rb2_water = ds_water.GetRasterBand(2)
band2_water_tmp = rb2_water.ReadAsArray()
band2_water = band2_water_tmp.tolist()
rb3_water = ds_water.GetRasterBand(3)
band3_water_tmp = rb3_water.ReadAsArray()
band3_water = band3_water_tmp.tolist()
[cols_water,rows_water] = band1_water_tmp.shape
loop_water_cols = 0
while loop_water_cols < cols_water:
loop_water_rows = 0
while loop_water_rows < rows_water:
dataset.append([band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0])
loop_water_rows = loop_water_rows +1
del dataset[0]
with open('path/dataset.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(dataset)
f.close()
dataset= [None]
loop_water_cols = loop_water_cols +1
dir_loop_water= dir_loop_water+1
With the above code, I want to add lists with length 4 to dataset.
but i print dataset's value(print(dataset[number])), it print like this.
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0]
[0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
In my opinion of above code, I add one list with four values.
However, the result is a combination of two lists with four values.
I could not find where the list would be merged.
Thanks for letting me know how to add only one list with 4 values at a time.
Your dataset.append() method is appending the entire list into your list (making a list of lists).
To append each item of the new list into the dataset (If I'm understanding you correctly) use += like so:
dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0]
this will result in a list like so:
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]

Python-saving while loop results [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hello i am trying to save the printed results from this while loop and then upload them to a database
i=0
x=0
n=0
while x < len(round1):
n +=1
print 'match number',n, ':' ,round1[x],scoretop[i],'VS','team:', round1[x+1],scorebottom[i],"\n"
x=x+2
i=i+1
i am totally new to python so sorry if this is an easy question
If you're on some UNIX-like system you can run this and redirect the output to a file like this:
python your-file.py > output.txt
Then you can manually upload the output to your database.
If you want to upload the results automatically you should safe the results in a list, instead of printing them, and then upload them through the API of your database. Look at dg123's answer for details on saving you results in a list.
Make a data structure beforehand and append to it while you are in the loop:
results = [] # A list of the results that
# that we will get in the while loop
i=0
x=0
n=0
while x < len(round1):
n +=1
results.append(' '.join(map(str,
['match number',
n,
':' ,
round1[x],
scoretop[i],
'VS','team:',
round1[x+1],scorebottom[i],"\n"])))
x=x+2
i=i+1
The results will then be saved in the results list, which you can then loop over and send to the database:
for i in results:
send_to_database(i)
Or you can concatenate all the strings together and send them that way if you like:
send_to_database('\n'.join(results))
I assume you want to print to file, you can simply write to a file:
with open('log.txt', 'w') as outfile:
while x < len(round1):
# some operations
out = ' '.join(map(str, ['match number', n, ':', round1[x], scoretop[i], 'VS', 'team:', round1[x+1], scorebottom[i], "\n"]))
outfile.write(out)
If you are working on UNIX machines, just follow the suggestion of #Ich Und Nicht Du

Categories

Resources