How to Convert list of string to tuple in python - python-3.x

I am facing a problem to convert from List to tuple. For example i have lists like this
['1', '9']
['2']
['3']
['4']
I want output like this
[(1,9),(2),(3),(4)]
Kindly help me. I am not getting any way.

If you have a list 'l' then you can call the builtin function 'tuple' on it to convert to a tuple
l = [1,2]
tup = tuple(l)
print tup # (1,2)
if you have a list of list l = [['1', '9'], ['2'], ['3'], ['4']]
you can do :
l = [['1', '9'], ['2'], ['3'], ['4']]
tups = map(lambda x: tuple(x), l)
print tups # [(1,9),(2),(3),(4)]

Related

Retrieving repeated items in a list comprehension

Given a sorted list, I would like to retrieve the first repeated item in the list using list comprehension.
So I ran the line below:
list=['1', '2', '3', 'a', 'a', 'b', 'c']
print(k for k in list if k==k+1)
I expected the output "a". But instead I got:
<generator object <genexpr> at 0x0021AB30>
I'm pretty new at this, would someone be willing to clarify why this doesn't work?
You seem to confuse the notion of list element and index.
For example the generator expression iterating over all items of list xs equal to its predecessor would look like this:
g = (xs[k] for k in range(1, len(xs)) if xs[k] == xs[k - 1])
Since you are interested only in first such item, you could write
next(xs[k] for k in range(1, len(xs)) if xs[k] == xs[k - 1])
however you'll get an exception if there is in fact no such items.
As a general advice, prefer simple readable functions over clever long one-liners,
especially when you are new to language. Your task could be accomplished as follows:
def first_duplicate(xs):
for k in range(1, len(xs)):
if xs[k] == xs[k - 1]:
return xs[k]
chars = ['1', '2', '3', 'a', 'a', 'b', 'c']
print(first_duplicate(chars)) # 'a'
P.S. Beware using list as your variable name -- you're shadowing built-in type
If you want just the first repeated item in the list you can use the next function with a generator expression that iterates through the list zipped with itself but with an offset of 1 to compare adjacent items:
next(a for a, b in zip(lst, lst[1:]) if a == b)
so that given lst = ['1', '2', '3', 'a', 'a', 'b', 'c'], the above returns: 'a'.

convert list of key/value strings into map python

Convert list of key/value strings into map. Assume that the list contains only strings and that each string has exactly one ':' .
Is the following code a good approach? Does anyone know of a more elegant solution to this?
>>> l = ['name:number']
>>> l = {x[:x.find(':')] : x[x.find(':')+1:] for x in l}
>>> print(l)
{'name': 'number'}
An even simpler approach:
>>> l = ['name:number']
>>> dict(x.split(':') for x in l)
{'name': 'number'}

Printing list containing a string

I am trying to store a string variable containg some names, I want to store the respective variable in a list and print it, but am unable print the values which are stored in variable.
name='vsb','siva','anand','soubhik' #variable containg some names
lis=['name'] # storing the variable in a list
for x in lis:
print(x) #printing the list using loops
Image:
Maybe dictionary? Try this
variable_1 = "aa"
variable_2 = "bb"
lis = {}
lis['name1'] = variable_1
lis['name2'] = variable_2
for i in lis:
print(i)
print(lis[i])
Your name variable is actually a tuple.
Example of tuple declaration:
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
Example of list declaration:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
For a better understanding you should read The Python Standard Library or do a tutorial.
For your problem maybe the dictionary is the solution:
# A tuple is a sequence of immutable Python objects
name='vsb','siva','anand','soubhik'
print('Tuple: ' + str(name)) # ('vsb', 'siva', 'anand', 'soubhik')
# This is a list containing one element: 'name'
lis=['name']
print('List: ' + str(lis)) # ['name']
# Dictionry with key 'name' and vlue ('vsb','siva','anand','soubhik')
dictionary={'name':name}
print('Dictionary: ' + str(dictionary))
print('Dictionary elements:')
print(dictionary['name'])
print('Tuple elements:')
for x in name:
print(x)
print('List elements:')
for x in lis:
print(x)
Output
Tuple: ('vsb', 'siva', 'anand', 'soubhik')
List: ['name']
Dictionary: {'name': ('vsb', 'siva', 'anand', 'soubhik')}
Dictionary elements:
('vsb', 'siva', 'anand', 'soubhik')
Tuple elements:
vsb
siva
anand
soubhik
List elements:
name

Dividing the list in Python and print the combinations

If i have a list in python, i want to divide the list into sub lists of some size 's' and then produce all the combinations of the sub_lists of size 2.
E.g :
Input: List = ['1','2','3','4']
sub-list size s = 3
My Output should be :
Sub-List-1 = ['1','2','3']
Combinations-1 = [('1','2'),('1','3'),('2','3')]
Sub-List-2 = ['2','3','4']
Combinations-2 = [('2','3'),('2','4'),('3','4')]
I tried this, but it did not work:
combination_list = []
while (myList):
sub_list = []
sub_list.append(myList[:s])
myList = myList[s:]
combination_list.append(combinations(sub_list, 2))
My Logic is :
Create an empty List for Combination
While my original List is not empty
Create an empty list for Sub lists
Append the s items to the sub lists
Remove s items from my original List(the items present in my sub list)
Produce the combinations of elements in my sub Lists
But i am not getting an expected output. Could someone help me with this please?
you can try this, i hope it helps
import itertools
mylist = ['1','2','3','4']
ls =[]
for i in range(0,int(len(mylist)/2)):
ls.append([mylist[i],mylist[i+1],mylist[i+2]])
print(len(ls)) /just getting the length to know how many sublist you have
sub1 = ls[0]
sub2 = ls[1]
comb1 =[]
comb2 =[]
//using itertools
comb1 = list(itertools.combinations(sub1,2))
comb2 = list(itertools.combinations(sub2,2))
print("combinations")
print(comb1)
print(comb2)
// if you want to use any import then you can use for-loop to do the
logic
ncomb = []
for i in range(len(sub1)-1):
for a in range(i,len(sub1)-1):
ncomb.append((sub1[i],sub1[a+1]))
print(ncomb) // output the same [('1', '2'), ('1', '3'), ('2', '3')]
//or better with List comprehension
lsize = len(sub1)
listcomp = [(sub1[x],sub1[y+1]) for x in range(lsize-1) for y in range(x,lsize-1)]
print(listcomp) // output the same [('1', '2'), ('1', '3'), ('2', '3')]
combinations
[('1', '2'), ('1', '3'), ('2', '3')]
[('2', '3'), ('2','4'), ('3', '4')]
result_list = []
combination_list = []
for i in range(len(myList)-s+1):
result_list.clear()
for j in range(i,i+s):
result_list.append(myList[j])
for i in combinations(result_list, 2):
combination_list.append((i[0],i[1]))
I got what is expected with the above piece of code!!But if you think it can be improved or there's something wrong with the code, please let me know!!

Matrix input from a text file(python 3)

Im trying to find a way to be able to input a matrix from a text file;
for example, a text file would contain
1 2 3
4 5 6
7 8 9
And it would make a matrix with those numbers and put it in matrix = [[1,2,3],[4,5,6],[7,8,9]]
And then this has to be compatible with the way I print the matrix:
print('\n'.join([' '.join(map(str, row)) for row in matrix]))
So far,I tried this
chemin = input('entrez le chemin du fichier')
path = input('enter file location')
f = open ( path , 'r')
matrix = [ map(int,line.split(','))) for line in f if line.strip() != "" ]
All it does is return me a map object and return an error when I try to print the matrix.
What am I doing wrong? Matrix should contain the matrix read from the text file and not map object,and I dont want to use external library such as numpy
Thanks
You can use list comprehension as such:
myfile.txt:
1 2 3
4 5 6
7 8 9
>>> matrix = open('myfile.txt').read()
>>> matrix = [item.split() for item in matrix.split('\n')[:-1]]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>>
You can also create a function for this:
>>> def matrix(file):
... contents = open(file).read()
... return [item.split() for item in contents.split('\n')[:-1]]
...
>>> matrix('myfile.txt')
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>>
is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)
rows=3
cols=3
with open('in.txt') as f:
data = []
for i in range(0, rows):
data.append(list(map(int, f.readline().split()[:cols])))
print (data)

Resources