Convert elements of a list in tuples - python

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)]

Related

convert list of integers in string format to list of integers in python

I have a list which looks like below
lis = '[-3.56568247e-02 -3.31957154e-02\n 7.04742894e-02\n 7.32413381e-02\n 1.74463019e-02]' (string type)
'\n' is also there in the list.
I need to convert this to actual list of integers
lis = [-3.56568247e-02,-3.31957154e-02 ,7.04742894e-02 ,7.32413381e-02, 1.74463019e-02] (list of integers)
I am doing the functionality, but it is failing
import as
res = ast.literal_eval(lis)
Can anyone tell me how to resolve this?
We can use re.findall along with a list comprehension:
lis = '[-3.56568247e-02 -3.31957154e-02 7.04742894e-02 7.32413381e-02\n 1.74463019e-02]'
output = [float(x) for x in re.findall(r'\d+(?:\.\d+)?(?:e[+-]\d+)?', lis)]
print(output)
# [0.0356568247, 0.0331957154, 0.0704742894, 0.0732413381, 0.0174463019]
You can try
[int(i) for i in lis.strip("[]").split(" ")]
You risk getting 1000 ways to do this.
This is a quick and easy way using only basic methods:
lis = '[1 2 3 4 5 77]'
elements = lis.replace('[','').replace(']','').split(' ')
my_ints = [int(e) for e in elements]
print(my_ints)

Change string in list to floats

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)

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]

Sum all numbers in a list of strings

sorry if this is very noob question, but I have tried to solve this on my own for some time, gave it a few searches (used the "map" function, etc.) and I did not find a solution to this. Maybe it's a small mistake somewhere, but I am new to python and seem to have some sort of tunnel vision.
I have some text (see sample) that has numbers inbetween. I want to extract all numbers with regular expressions into a list and then sum them. I seem to be able to do the extraction, but struggle to convert them to integers and then sum them.
import re
df = ["test 4497 test 6702 test 8454 test",
"7449 test"]
numlist = list()
for line in df:
line = line.rstrip()
numbers = re.findall("[0-9]+", line) # find numbers
if len(numbers) < 1: continue # ignore lines with no numbers, none in this sample
numlist.append(numbers) # create list of numbers
The sum(numlist) returns an error.
You don't need a regex for this. Split the strings in the list, and sum those that are numeric in a comprehension:
sum(sum(int(i) for i in s.split() if i.isnumeric()) for s in df)
# 27102
Or similarly, flatten the resulting lists, and sum once:
from itertools imprt chain
sum(chain.from_iterable((int(i) for i in s.split() if i.isnumeric()) for s in df))
# 27102
This is the source of your problem:
finadall returns a list which you are appending to numlist, a list. So you end up with a list of lists. You should instead do:
numlist.extend(numbers)
So that you end up with a single list of numbers (well, actually string representations of numbers). Then you can convert the strings to integers and sum:
the_sum = sum(int(n) for n in numlist)
Iterate twice over df and append each digit to numlist:
numlist = list()
for item in df:
for word in item.split():
if word.isnumeric():
numlist.append(int(word))
print(numlist)
print(sum(numlist))
Out:
[4497, 6702, 8454, 7449]
27102
You could make a one-liner using list comprehension:
print(sum([int(word) for item in df for word in item.split() if word.isnumeric()]))
>>> 27102
It's as easy as
my_sum = sum(map(int, numbers_list))
Here is an option using map, filter and sum:
First splits the strings at the spaces, filters out the non-numbers, casts the number-strings to int and finally sums them.
# if you want the sum per string in the list
sums = [sum(map(int, filter(str.isnumeric, s.split()))) for s in df]
# [19653, 7449]
# if you simply want the sum of all numbers of all strings
sum(sum(map(int, filter(str.isnumeric, s.split()))) for s in df)
# 27102

Does string contain any of the words in my list?

I want to check a string to see if it contains any of the words i have in my list.
the list is has somewhere around 100 individual words.
i have tried using regex but cant get it to work...
string = "<div class="header_links">$$ - $$$, Dansk, Veganske retter, Glutenfri retter</div>"
list = ['Café','Afrikansk','............','Sushi','Svensk','Sydamerikansk','Syditaliensk','Szechuan','Taiwansk','Thai','Tibetansk','Østeuropæisk','Dansk']
in this case the string has 'Dansk' in it. The string could contain more than one of the words in the list.
i want to write a piece of code that prints the words in the list which is also in the string.
in this case the output should be: Dansk
if there was more than one word in the string it should be: Dansk, ...., ....
I hope someone can help
>>> list = ['Café','Afrikansk','............','Sushi','Svensk','Sydamerikansk','Syditaliensk','Szechuan','Taiwansk','Thai','Tibetansk','Østeuropæisk','Dansk']
>>> string = """<div class="header_links">$$ - $$$, Dansk, Veganske retter, Glutenfri retter</div>"""
>>> [x for x in list if x in string]
['Dansk']
I recommend not using list as a variable name, as it usually referring to the type list (like str or int)
Use a list comprehension with a membership check:
[x for x in lst if x in string]
Note that I have renamed your list to lst, as list is built-in.
Example:
string = '<div class="header_links">$$ - $$$, Dansk, Veganske retter, Glutenfri retter</div>'
lst = ['Café','Afrikansk','Sushi','Svensk','Sydamerikansk','Syditaliensk','Szechuan','Taiwansk','Thai','Tibetansk','Østeuropæisk','Dansk']
print([x for x in lst if x in string])
# ['Dansk']
in your case you can use:
string_intersection = set(string.replace(',', '').split()).intersection(my_list)
print(*string_intersection, sep =',')
output:
Dansk

Categories

Resources