How to convert list pairs into tuple pairs - python

How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?
My code:
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
return numbers
desire output:
[(68,125), (113,69), (65,86), (108,149), (152,53), (78,90)]

def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
return [tuple(map(int,pair.split(','))) for pair in numbers]

Try this by using nested list comprehension:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]

Just use list comprehension. Read more about it here!
# Pass in numbers as an argument so that it will work
# for more than 1 list.
def read_numbers(numbers):
return [tuple(int(y) for y in x.split(",")) for x in numbers]
Here is a breakdown and explanation (in comments) of the list comprehension:
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
However, if you are just doing it for one list, there is no need to create a function.

Try this :
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
final_list = []
[final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
return final_list

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]

how to filter a value from list in python?

I have list of values , need to filter out values , that doesn't follow a naming convention.
like below list : list = ['a1-23','b1-24','c1-25','c1-x-25']
need to filter : all values that starts with 'c1-' , except 'c1-x-' )
output expected: ['a1-23','b1-24','c1-x-25']
list = ['a1-23','b1-24','c1-25','c1-x-25']
[x for x in list if not x.startswith('c1-')]
['a1-23', 'b1-24']
You have the right idea, but you're missing the handing of values that start with c1-x-:
[x for x in list if not x.startswith('c1-') or x.startswith('c1-x-')]
import re
list1 = ['a1-23','b1-24','c1-25','c1-x-25',"c1-22"]
r = re.compile(r"\bc1-\b\d{2}$") # this regex matches anything with `c1-{2 digits}` exactly
[x for x in list1 if x not in list(filter(r.match,list1))]
# output
['a1-23', 'b1-24', 'c1-x-25']
So what my pattern does is match EXACTLY a word that starts with c1- and ends with two digits only.
Therefore, list(filter(r.match,list1)) will give us all the c1-## and then we do a list comprehension to filter out from list1 all the x's that aren't in the new provided list containing the matches.
x for x in [1,2,3] if x not in [1,2]
#output
[3]

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]

String matching in lists - Python

I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)
test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUsage_20150317
test:SF.ClientUsage_20150318
test:SF.ClientUsage_20150319
test:SF.ClientUsage_20150320
test:SF.ClientUsage_20150321
I am using this for loop but not sure why it does not work:
for x in list:
if(x 'test:SF.AcuraUsage_'):
print x
I tried this out:
for x in list:
alllist = x
vehiclelist = [x for x in alllist if x.startswith('geotab-bigdata-test:StoreForward.VehicleInfo')]
Still i get the error ' dictionary object has no attribute startswith'.
You shouldn't name your list list, since it overrides the built-in type list
But, if you'd like to filter that list using Python, consider using this list comprehension:
acura = [x for x in list if x.startswith('test:SF.AcuraUsage')]
then, if you'd like to output it
for x in acura:
print(x)
List comprehensions are good for that.
Get a list with all the items that begin with 'test:SF.AcuraUsage_' :
new_list = [x for x in list if x.startswith('test:SF.AcuraUsage_' ')]
Or the items that do not begin with 'test:SF.AcuraUsage_' :
new_list = [x for x in list if not x.startswith('test:SF.AcuraUsage_' )]
using re module:
import re
for x in list:
ret = re.match('test:SF.AcuraUsage_(.*)',x)
if ret:
print(re.group())

Function Definition: Matching two input lists

def match_numbers (nlist, nlist1):
'''Returns the integer string whose first three numbers are on the first list'''
for x in nlist:
for x in nlist1:
print(x)
So suppose the first list was ['543', '432'] and the second list had ['543242', '43299919', '2322242', '245533'], and I need the function to match 543 and 432 with its longer version on the second list, how can I get my code to do this?
If you have a large list, this will perform slightly better
list1 = ['543', '432']
list2 = ['543242', '43299919', '2322242', '245533']
def match_numbers (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print results[x]
match_numbers(list1, list2)
Try this:
[x for x in a for i in b if i == x[:len(i)]]
Output:
['543242', '43299919']

Categories

Resources