How to convert following list
['abc,cde,eg,ba', 'abc,cde,ba']
in to list of tuples?
[('abc','cde','eg','ba'), ('abc','cde','ba')]
What I have tried
output = []
for item in my_list:
a = "','".join((item.split(',')))
output.append(a)
In your loop, you are splitting the string (which will give you a list), but then you are joining it back with a ,, which is returning to you the same string:
>>> 'a,b'.split(',')
['a', 'b']
>>> ','.join('a,b'.split(','))
'a,b'
You can convert a list to a tuple by passing it to the the built-in tuple() method.
Combining the above with a list comprehension (which is an expression that evaluates to a list), gives you what you need:
>>> [tuple(i.split(',')) for i in ['abc,cde,eg,ba', 'abc,cde,ba']]
[('abc', 'cde', 'eg', 'ba'), ('abc', 'cde', 'ba')]
The longhand way of writing that is:
result = []
for i in ['abc,cde,eg,ba', 'abc,cde,ba']:
result.append(tuple(i.split(',')))
print(result)
t=['abc,cde,eg,ba', 'abc,cde,ba']
for i in t:
print tuple(i.split(','))
you can split the 2 elements. Here is my code
['abc,cde,eg,ba', 'abc,cde,ba']
a='abc,cde,eg,ba'
b='abc,cde,ba'
c=[]
c.append(tuple(a.split(',')))
c.append(tuple(b.split(',')))
print c
Related
I'm trying to do an exercise where I have a list:
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
And I have to make a second list out of it that looks like this:
list_2 = [['chocolate', 1.20], ['book', 5.50], ['hat', 3.25]]
In the second list the numbers have to be floats and without the ' '
So far I've come up with this code:
for item in list_1:
list_2.append(item.split(';'))
The output looks about right:
[['chocolate', '1.20'], ['book', '5.50'], ['hat', '3.25']]
But how do I convert those numbers into floats and remove the double quotes?
I tried:
for item in list_2:
if(item.isdigit()):
item = float(item)
Getting:
AttributeError: 'list' object has no attribute 'isdigit'
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [x.split(';') for x in list_1]
list_3 = [[x[0], float(x[1])] for x in list_2]
item is a list like ['chocolate', '1.20']. You should be calling isdigit() on item[1], not item. But isdigit() isn't true when the string contains ., so that won't work anyway.
Put the split string in a variable, then call float() on the second element.
for item in list_1:
words = item.split(';')
words[1] = float(words[1])
list_2.append(words)
I don't know if this helpful for you.
But,I think using function is better than just using simple for loop
Just try it.
def list_map(string_val,float_val):
return [string_val,float_val]
def string_spliter(list_1):
string_form=[]
float_form=[]
for string in list_1:
str_val,float_val=string.split(";")
string_form.append(str_val)
float_form.append(float_val)
return string_form,float_form
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
string_form,float_form=string_spliter(list_1)
float_form=list(map(float,float_form))
output=list(map(list_map,string_form,float_form))
print(output)
Your way of creating list_2 is fine. To then make your new list, you can use final_list = [[i[0], float(i[1])] for i in list_2]
You could also do it in the for loop like this:
for item in list_1:
split_item = item.split(';')
list_2.append([split_item[0], float(split_item[1])])
This can be achieved in two lines of code using list comprehensions.
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [[a, float(b)] for x in list_1 for a, b in [x.split(';', 1)]]
The second "dimension" to the list comprehension generates a list with a single sublist. This lets us essentially save the result of splitting each item and then bind those two items to a and b to make using them cleaner that having to specify indexes.
Note: by calling split with a second argument of 1 we ensure the string is only split at most once.
You can use a function map to convert each value.
def modify_element(el):
name, value = el.split(';')
return [name, float(value)]
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
result = list(map(modify_element, list_1))
For a problem like this you can initialize two variables for the result of calling the split function and then append a list of both values and call the builtin float function on the second value.
array = []
for i in a_list:
string, number = i.split(";")
array.append([string, float(number)])
print(array)
I want to write a function that takes a list of strings, sort the letters in each string, and then sort the full list.
So I created a list of strings "a". This code works perfectly, but is there any way to split the code for b variable? I want this function to sort the letters in each string first and then sort the full list.
a = ['hi' , 'hello', 'at', 'this', 'there', 'from']
def string_fun(a):
for i in a:
b= sorted(''.join(sorted(i)) for i in a)
return(b)
string_fun(a)
I was trying this:
a = ['hi' , 'hello', 'at', 'this', 'there', 'from']
def string_fun(a):
for i in a:
b=''.join(sorted(i))
for i in b:
c= sorted()
return(c)
string_fun(a)
But I get an error "sorted expected 1 argument, got 0"
You are misunderstanding the syntax for for-loops in python. When you write for x in a, variable x is not an index to be used to get an element as a[x]. Variable x is the element.
So you can write:
result = []
for x in a:
result.append(''.join(sorted(x)))
result.sort()
Or equivalently:
result = []
for i in range(len(a)):
result.append(''.join(sorted(a[i])))
result.sort()
Or equivalently, use a list comprehension:
result = sorted(''.join(sorted(x)) for x in a)
Please take some time to read more about loops and list comprehensions in python:
loops in python;
list comprehensions.
Trying to convert this string (put in the variable a1):
'\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
to:
'\'start\':\'redis_import\',\'dim_user_level\':\'redis_import\''
I have tried print a1.split(',').reverse() but this returns null. Why? and how to achieve this without using a loop?
Any help is appreciated.
If you want it as a dict.
s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
res = {}
for i in s.split(","):
val = list(reversed(i.split(":")))
res[val[0].replace("'", "")] = val[1].replace("'", "")
print(res)
Output:
{'start': 'redis_import', 'dim_user_level': 'redis_import'}
First of all .reverse() method reverse the list and returns None
so you can use reversed() which will return you iterator of reverse of the list
a = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
print(', '.join([':'.join(reversed(i.split(':'))) for i in a.split(',')])) # "'start':'redis_import', 'dim_user_level':'redis_import'"
Split on comma, split on colons, reverse, join colons, join commas:
s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
','.join(':'.join(i.split(':')[::-1]) for i in s.split(','))
#"'start':'redis_import','dim_user_level':'redis_import'"
To understand this better just observe the output of these different calls:
>>> s.split(',')
["'redis_import':'start'", "'redis_import':'dim_user_level'"]
>>> s.split(',')[0]
"'redis_import':'start'"
>>> s.split(',')[0].split(':')
["'redis_import'", "'start'"]
>>> s.split(',')[0].split(':')[::-1]
["'start'", "'redis_import'"]
>>> ','.join(('a', 'b', 'c'))
'a,b,c'
>>> [i[::-1] for i in [[1,2], [3,4]]]
[[2, 1], [4, 3]]
Some further reading:
str.split - the method used to separate the strings at delimiters
str.join - the method used to join iterables back to strings
a good introduction to those one-line generator expressions
a section about slicing and how they can be used to reverse sequences
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
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.