Change string in list to floats - python

I have a list as follows:
pos = ['52.1,13.3','53.2,14.3',....,'55.3,16.4']
I want to change each string in the list to a float, such that I get the following:
pos = [52.1,13.3,53.2,14.3,....,55.3,16.4]
I am using the following loop:
b = []
for str in a:
str = float(str)
b.append(str)
print (b)
Which raises the following error
ValueError: could not convert string to float: '52.1,13.3'
How do I change the strings into separate floats in a new list?

You have to split the strings at the comma and apply float to each of the entries. Then extend the list with those floating point values.
pos = ['52.1,13.3','53.2,14.3','55.3,16.4']
lst = []
for entry in pos:
lst.extend(map(float, entry.split(',')))
print(lst)
This will give you [52.1, 13.3, 53.2, 14.3, 55.3, 16.4].
If you're unfamiliar with map you should learn how to use it. But nevertheless here's a version with a loop approach:
lst = []
for entry in pos:
for value in entry.split(','):
lst.append(float(value))
print(lst)

Related

Incorrect number of values in output from zip?

I've been working on a problem that involves taking multiple number pairs, and creating some form of sum loop that adds each pair together.
I am not getting the correct number of outputs, e.g. 15 pairs of numbers are inputted and only 8 are coming out.
Here's my code so far...
data = "917128 607663\
907859 281478\
880236 180499\
138147 764933\
120281 410091\
27737 932325\
540724 934920\
428397 637913\
879249 469640\
104749 325216\
113555 304966\
941166 925887\
46286 299745\
319716 662161\
853092 455361"
data_list = data.split(" ") # creating a list of strings
data_list_numbers = [] # converting list of strings to list of integers
for d in data_list:
data_list_numbers.append(int(d))
#splitting the lists into two with every other integer (basically to get the pairs again.
list_one = data_list_numbers[::2]
list_two = data_list_numbers[1::2]
zipped_list = zip(list_one, list_two) #zipping lists
sum = [x+y for x,y in zip(list_one, list_two)] # finding the sum of each pair
print(sum)
What am I missing?
Quote the input string like so: """...""", remove the backslashes, and use re.split to split on whitespace. Note that using backslashes without spaces, as you did, causes the numbers in data to smash into each other. That is, this:
"607663\
907859"
is the same as: "607663907859".
import re
data = """917128 607663
907859 281478
880236 180499
138147 764933
120281 410091
27737 932325
540724 934920
428397 637913
879249 469640
104749 325216
113555 304966
941166 925887
46286 299745
319716 662161
853092 455361"""
data_list = re.split(r'\s+', data) # creating a list of strings
data_list_numbers = [] # converting list of strings to list of integers
for d in data_list:
data_list_numbers.append(int(d))
#splitting the lists into two with every other integer (basically to get the pairs again.
list_one = data_list_numbers[::2]
list_two = data_list_numbers[1::2]
zipped_list = zip(list_one, list_two) #zipping lists
sum = [x+y for x,y in zip(list_one, list_two)] # finding the sum of each pair
print(sum)
# [1524791, 1189337, 1060735, 903080, 530372, 960062, 1475644, 1066310, 1348889, 429965, 418521, 1867053, 346031, 981877, 1308453]

Sort a list trough a function from user's input

I am trying to write a function which takes as argument a list of integers from the user input and sorts them.
I am getting some issues, because if I convert the integers to strings (I thought it could be the best way, because of the commas in the input) and append them in an empty list, I get an error.
Here the function:
def sort_integers(x):
lst = []
for i in x:
lst.append(i)
sorted_list = sorted(lst)
print(sorted_list)
sort_integers(str(input("Enter some numbers: ")))
But if I enter 10, 9, 8 as integers, this is what I get as output:
[',', ',', '0', '1', '8', '9']
Expected output would be: 8,9,10. I have tried to use sort_integers(int(input("Enter some numbers: "))) but I get this error:
ValueError: invalid literal for int() with base 10: '10,9,8'
What am I doing wrong?
You are only interested in digits and when you use for loop you state the that for each symbol in my string add it to a list, , and ( space ) is a symbol to Python.
Using str.split() on a string returns a list with the elements from the string, have a read on it. split() accepts an argument that you want to split your string on, in your case its ,.
To achieve your result you can use the following:
def sort_integers(x):
return sorted([x for x in x.split(',') if x.isdigit()])
I am returning the sorted list which is built from the string you pass to your function and taking only digits using str.isdigit() built-in method.
Also, you do not need to use str(input() because input() always returns a string no matter what you pass to it.
Try this:
def sort_integers(x):
x = x.split(',')
sorted_list = sorted([int(i) for i in x])
print(sorted_list)
sort_integers(str(input("Enter some numbers: ")))
Or this (minimal change in your existing code)
def sort_integers(x):
x = x.split(',')
lst = []
for i in x:
lst.append(int(i))
sorted_list = sorted(lst)
print(sorted_list)
sort_integers(str(input("Enter some numbers: ")))
Output:
Enter some numbers: 10,9,8
[8, 9, 10]

How to search through an arry containing strings, and create a new array with only integers

If I have an array that contains only strings, but some of them are numbers, how would I search through the array, determine which strings are actually numbers, and add those numbers to a new array? An example of the array is as follows: [ "Chris" , "90" , "Dave" , "76" ]
I have tried using a for loop to consecutively use isdigit() on each index, and if it is true to add that item to the new array.
scores = []
for i in range(len(name_and_score_split)):
if name_and_score_split[i].isdigit() == True:
scores.append(name_and_score_split[i])
When the above code is ran it tells me list data type does not have the "isdigit" function
edit: iv'e found that my problem is the list is actually a list of lists.
Use a list-comprehension and also utilise the for-each property of Python for rather than iterating over indices:
lst = ["Chris" , "90" , "Dave" , "76"]
scores = [x for x in lst if x.isdigit()]
# ['90', '76']
Alternately, filter your list:
scores = list(filter(lambda x: x.isdigit(), lst))
Assuming what you're trying if for integers you can do something like:
// Taken from and changing float by int.
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
Then you can do
[x for x in name_and_score_split if is_number(x)]
If you want list of int:
s = ["Chris", "90", "Dave", "76"]
e = [int(i) for i in s if i.isdigit()]
print(e)
# OUTPUT: [90, 76]

How to remove a string from a list python

Is it possible to remove the string and just have the list
data = [
"50,bird,corn,105.4,"
"75,cat,meat,10.3,"
"100,dog,eggs,1000.5,"
]
would like it to look like this
data = [
50,'bird','corn',105.4,
75,'cat','meat',10.3,
100,'dog','eggs',1000.5,
]
out = []
for x in data:
for e in x.split(","):
out.append(e)
What does this do? It splits each element (x) in data on the comma, picks out each of those separate tokens (e), and puts them in the variable (out.append).
new_data = []
for i in data:
new_data.extend(i.split(','))
new_data
Do note that there might be issues (for example, you have one last comma with nothing after it, so it generates a '' string as the last element in the new array).
If you want to specifically convert the numbers to ints and floats, maybe there is a more elegant way, but this will work (it also removes empty cells if you have excess commas):
new_data = []
for i in data:
strings = i.split(',')
for s in strings:
if (len(s)>0):
try:
num = int(s)
except ValueError:
try:
num = float(s)
except ValueError:
num = s
new_data.append(num)
new_data
split each string (this gives you an array of the segments between "," in each string):
str.split(",")
and add the arrays together
Because each string in the list has a trailing comma, you can simply put it back together as a single string and split it again on commas. In order to get actual numeric items in the resulting list, you could do this:
import re
data = [
"50,bird,corn,105.4,"
"75,cat,meat,10.3,"
"100,dog,eggs,1000.5,"
]
numeric = re.compile("-?\d+[\.]\d*$")
data = [ eval(s) if numeric.match(s) else s for s in "".join(data).split(",")][:-1]
data # [50, 'bird', 'corn', 105.4, 75, 'cat', 'meat', 10.3, 100, 'dog', 'eggs', 1000.5]

Convert elements of a list in tuples

I have the following list:
list_c = ['42.2529, -73.7910', '42.079846, -76.499364', '42.361824, -73.597979', '42.035959, -73.580146']
I'd like to convert to this:
list_c2 = [(42.2529, -73.7910),(42.079846, -76.499364),(42.361824, -73.597979),(42.035959, -73.580146)]
The code am trying is:
list_c2 = [(list_c[i]) for i in range(0, len(list_c))]
print("list_c2 =", list_c)
Unfortunately, the result is exactly the same as list_c
I'm sorry, I misread you list initially. To convert this into pairs of floats, you'll need to split each string on its comma and then make each element a float, then pack them in a tuple:
list_c2 = [tuple(float(item) for item in s.split(',')) for s in list_c]
# [(42.2529, -73.791), (42.079846, -76.499364), (42.361824, -73.597979), (42.035959, -73.580146)]

Categories

Resources