list of strings to a tuple of ints - python

I'm new to python and am having trouble doing this conversion. How exactly do you convert a list of individual strings such as ['1','2'] and convert it to a tuple (1,2). If it was simply a list it would be simple to just use tuple(list_x) but this seems more complicated.

You can use the tuple constructor to make a tuple from a list:
X = ['1', '2']
myTuple = tuple(X)
myTuple is now a tuple of strings: ('1', '2').
If you want to get a tuple of integers, you must first convert your list to a list of integers, and then use the tuple constructor.
The int() function will convert a string to an int. We can use that plus a list comprehension to get what you want:
tuple([int(s) for s in X])

List ['1', '2'] can be converted to tuple by line below:
l = ['1','2']
tuple_from_l = tuple(map(int,l))
print tuple_from_l
Note: Before converting to tuple i've passed list to map to convert all item to int with int method

Related

Python convert array of strings to array of bytes

I am trying to convert an array of strings oldlist = ['00000100', '10100001', '11000001', '11100001'] that are binary values into bytes of their value as hex codes so the resulting list would look like this newlist = [b'\x04', b'\xa1', b'\xc1', b'\xe1']. I get the basic concept of looping through the first list and appended to the previous or doing some sort of list comp. But I can't find a function to convert "00000100" to " b'\x04' "
You can use int(number, 2) to convert the string to integer:
oldlist = ["00000100", "10100001", "11000001", "11100001"]
out = list(map(lambda x: bytes([int(x, 2)]), oldlist))
print(out)
Prints:
[b'\x04', b'\xa1', b'\xc1', b'\xe1']
what you can do is to use string.getBytes();
You first need to convert the binary string to an integer. For this you can use int() method with radix of 2. Then to convert that to bytes, use the bytes() method like this bytes([x]).
>>> oldlist = ['00000100', '10100001', '11000001', '11100001']
>>> list(map(lambda x: bytes([int(x, 2)]), oldlist))
[b'\x04', b'\xa1', b'\xc1', b'\xe1']

Python list of tuples with variable length: Get string representation of tuples holding only object attributes

I have a list of tuples that consist of objects of a certain class and differ in their dimension:
my_list = [(obj1, obj2), (obj3, obj1), (obj4, obj1), (obj2,),...]
All of these objects have an attribute label which is of type string and holds an object label e.g. 'object_1', 'object_2' and so on.
Now I want to extract the string representation of the tuples holding the attribute values (labels) e.g.:
my_new_list = ['(object_1, object_2)', '(object_3, object_1)', '(object_4, object_1)', '(object_2,)', ...]
I have looked up how to extract a list of attributes from a list of objects and how to convert a tuple to string and would probably achieve my goal with some nested for loops. But I got stuck in some messy code here..
But isn't there some nice pythonic way to do this?
Thanks in advance!
*EDIT: Some of the tuples are one dimensional e.g. (obj2,). Sorry, I forgot that and now have adapted my question!
You can do
["(%s, %s)" %(i.label, j.label) for i, j in my_list]
If dynamic length inside tuple:
["(%s)" %", ".join([j.label for j in i]) for i in my_list]
The two other simple list comprehension answers work fine for an arbitrary list of tuples of objects with the attribute. However, Python has some great built-in functionality which let you choose the string representation of your objects, and most built-in types have this already. For example, any tuple can be cast to it's string representation just by encasing the tuple with str(tuple):
>>> str((5, 4))
'(5, 4)'
Now, if you did this with a tuple of arbitrary objects, then you'd get a string which has the actual object handle like <__main__.YourClass object at 0x10ad58fd0> which is ugly. But, if you provide a __repr__ function inside your class definition, then you can change that standard handle to something you like instead. In this case, your label seems like a good candidate to return for the string representation of your object. Here's a minimal example created with your same code:
class LabeledObj:
def __init__(self, label):
self.label = label
def __repr__(self):
return self.label
obj1 = LabeledObj('object_1')
obj2 = LabeledObj('object_2')
obj3 = LabeledObj('object_3')
obj4 = LabeledObj('object_4')
my_list = [(obj1, obj2), (obj3, obj1), (obj4, obj1), (obj2,)]
my_new_list = [str(obj_tuple) for obj_tuple in my_list]
print(my_new_list)
['(object_1, object_2)', '(object_3, object_1)', '(object_4, object_1)', '(object_2,)']
Now I think this is very pythonic and very clear later in the code, and defining the __repr__ only takes an additional two lines of code. And now you can print(my_obj) instead of print(my_obj.label) which reads nicely.
You can use list comprehension for that:
['({}, {})'.format(el1.label, el2.label) for el1, el2 in my_list]
To not depend from tuple dimension use helper function:
def tuple_print(tup):
return '({})'.format(', '.join(t.label for t in tup))
my_new_list = [tuple_print(tup) for tup in my_list]
Tuple list elements count
using len() + generator expression
temp = list((int(j) for i in test_list for j in i))
res = len(temp)
You can use map function to help. This can be complete in one line of code
my_new_list = list(map(lambda P: '({})'.format(','.join(list(map(lambda t:t.label,list(P))))),my_list))
This also work with one dimension tuples.

Python: How to convert a list to a list of tuples?

for example, i have a list below,
['Visa', 'Rogers', 'Visa']
if i want to convert it to a list of tuples, like
[('Visa',), ('Rogers',), ('Visa',)]
How can I convert it?
>>> [(x,) for x in ['Visa', 'Rogers', 'Visa']]
[('Visa',), ('Rogers',), ('Visa',)]
simple list comprehension will do the trick. make sure to have the , to specify single item tuples (you will just have the original strings instead)
Doing some kind of operation for each element can be done with map() or list comprehensions:
a = ['Visa', 'Rogers', 'Visa']
b = [(v,) for v in a]
c = map(lambda v: (v,), a)
print(b) # [('Visa',), ('Rogers',), ('Visa',)]
print(c) # [('Visa',), ('Rogers',), ('Visa',)]
Please keep in mind that 1-element-tuples are represented as (value,) to distinguish them from just a grouping/regular parantheses

Convert list to string using python

I have the list it contain int ,float and string:
lists = [10, "test", 10.5]
How Can i convert above list to string? I have tried:
val = ','.join(lists)
print val
I am getting error like this:
sequence item 0: expected string, int found
How can I solve this issue?
Firstly convert integers to string using strusing map function then use join function-
>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'
Or if you want to convert each element of list into string then try-
>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']
Or use itertools for memory efficiency(large data)
>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']
Or simply use list comprehension
>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']
The easiest way is to send the whole thing to str() or repr():
>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"
repr() may produce a different result from str() depending on what's defined for each type of object in the list. The point of repr() is that you can send such strings back to eval() or ast.literal_eval() to get the original object back:
>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]
a = ['b','c','d']
strng = ''
for i in a:
strng +=str(i)
print strng
The error you are getting because join wants elements to be string type, but in your list there is integer too, so 1st you have to convert them to type string.
you can use list comprehension and str and join to join them
>>> lists = [10,"test",10.5]
>>> ",".join(str(x) for x in lists)
You have to pass each item in your list as a string into the ','.join(sequence). Consider using:
val = ','.join([str(item) for item in lists])
print val
If you want to convert each element in the list to a string, you could do it simply using a for-loop.
for i in range(len(lists)):
lists[i] = str(lists[i])
Alternatively, if you want to make one string where all elements are joined together, you could edit the code above slightly.
string_of_lists = ""
for i in lists:
string_of_lists += str(i)
As you can tell, this is another way of doing it, apart from the other solutions using join.
I hope I helped!
This is also possible. Here x variable is list.
>>> '%s'*len(x) % tuple(x)
As mentioned here
list=['a/b/c', 'd/e/f']
file_list_string= ' '.join(list)
file_list_string= ' '.join(str(file) for file in list)
import functools
lists = [10,"test",10.5]
print(functools.reduce(lambda x,y:x+","+y,list(map(str,lists))))
You could always do it the dirty way:
list_name = ["a", "b", "c"];
string_name = "";
for c in list_name:
string_name += c
print(string_name)
OUTPUT:
"abc"
That should work with ints, floats, and strings, always converting them to string type.

Convert string to int in a list by removing floating (Python)

I have a list like this:
List= [("Mike,"Admin","26,872"),
("John,"Admin","32,872"),
("Mark,"Admin","26,232")...]
what I want to achieve is the following:
List= [("Mike,"Admin", 26872),
("John,"Admin", 32872),
("Mark,"Admin", 26232)...]
so for the every third element I want to remove comma and convert it to int.
I tried for example to do replace but the list doesn't support replace method.
Just a test:
accounts = sorted(List, key=lambda account: account[2], reverse=True)
for i,j,k in accounts:
k.replace(",", "")
int k
Any ideas?
One way would be:
[(a, b, c.replace(",", "")) for a, b, c in List]
This will create a new list having the first two values unchanged, and the third with the comma being removed.
If you want to have the third value as an int, you can simply.. cast it.
Note that you can iterate on the list in a different way,
[(w[0], w[1], w[2]) for w in List]

Categories

Resources