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
Related
For example lets say I have a list as below,
list = ['list4','this1','my3','is2'] or [1,6,'one','six']
So now I want to change the index of each element to match the number or make sense as I see fit (needn't be number) like so, (basically change the index of the element to wherever I want)
list = ['this1','is2','my3','list4'] or ['one',1,'six',6]
how do I do this whether there be numbers or not ?
Please help, Thanks in advance.
If you don't wanna use regex and learn it's mini language use this simpler method:
list1 = ['list4','this1', 'he5re', 'my3','is2']
def mySort(string):
if any(char.isdigit() for char in string): #Check if theres a number in the string
return [float(char) for char in string if char.isdigit()][0] #Return list of numbers, and return the first one (we are expecting only one number in the string)
list1.sort(key = mySort)
print(list1)
Inspired by this answer: https://stackoverflow.com/a/4289557/11101156
For the first one, it is easy:
>>> lst = ['list4','this1','my3','is2']
>>> lst = sorted(lst, key=lambda x:int(x[-1]))
>>> lst
['this1', 'is2', 'my3', 'list4']
But this assumes each item is string, and the last character of each item is numeric. Also it works as long as the numeric parts in each item is single digit. Otherwise it breaks. For the second one, you need to define "how you see it fit", in order to sort it in a logic.
If there are multiple numeric characters:
>>> import re
>>> lst = ['lis22t4','th2is21','my3','is2']
>>> sorted(lst, key=lambda x:int(re.search(r'\d+$', x).group(0)))
['is2', 'my3', 'list4', 'this21']
# or,
>>> ['is2', 'my3', 'lis22t4', 'th2is21']
But you can always do:
>>> lst = [1,6,'one','six']
>>> lst = [lst[2], lst[0], lst[3], lst[1]]
>>> lst
['one', 1, 'six', 6]
Also, don't use python built-ins as variable names. list is a bad variable name.
If you just want to move element in position 'y' to position 'x' of a list, you can try this one-liner, using pop and insert:
lst.insert(x, lst.pop(y))
If you know the order how you want to change indexes you can write simple code:
old_list= ['list4','this1','my3','is2']
order = [1, 3, 2, 0]
new_list = [old_list[idx] for idx in order]
If you can write your logic as a function, you can use sorted() and pass your function name as a key:
old_list= ['list4','this1','my3','is2']
def extract_number(string):
digits = ''.join([c for c in string if c.isdigit()])
return int(digits)
new_list = sorted(old_list, key = extract_number)
This case list is sorted by number, which is constructed by combining digits found in a string.
a = [1,2,3,4]
def rep(s, l, ab):
id = l.index(s)
q = s
del(l[id])
l.insert(ab, q)
return l
l = rep(a[0], a, 2)
print(l)
Hope you like this
Its much simpler
Suppose we have a string:
A = "John\t20\nChris\t30\nAby\t10\n"
I want to make A into a list of list with the first element still str and second element converted to int:
What i have done is :
A = [[lambda k,v: str(k), int(v) for k, v in s.split('\t')] for s in A.split('\n')]
Any suggestion?
You can just get the values without lambda:
[[s.split('\t')[0], int(s.split('\t')[1])] for s in A.strip().split('\n')]
Note: strip() is added to parse out the trailing '\n'.
I think you are overcomplicating this. You don't need an anonymous function here at all.
First, split the string, then iterate over groups of two from the resulting list and convert the second element of the pairs to int.
For the second part, the itertools documentation has a recipe called grouper. You can either copy-paste the function or import it from more_itertools (which needs to be installed).
>>> from more_itertools import grouper
>>>
>>> a = "John\t20\nChris\t30\nAby\t10\n"
>>> [(s, int(n)) for s, n in grouper(2, a.split())]
[('John', 20), ('Chris', 30), ('Aby', 10)]
Finally, if you want to flatten the result, apply itertools.chain.
>>> list(chain.from_iterable((s, int(n)) for s, n in grouper(2, a.split())))
['John', 20, 'Chris', 30, 'Aby', 10]
If you like to use lambda, here's a simpler way;
L = lambda s: [s.split('\t')[0], int(s.split('\t')[1])]
A3 = [L(x) for x in A.strip().split('\n')]
I can't imagine I'm going to get much help from this due to my inability to explain it. But for instance I have a string like so:
s = "[1,[2,2,[3,4]],5]"
and I need to convert it into a nested list item as such
lst = ["1",["2","2",["3","4"]],"5"]
that if I were to go lst[1][2][0] it would return '3'.
The way I have tried to do it was by creating a substring for every number within '[' and end of string characters and then slowly nest it back up
def ParseList(strlist):
if '[' in strlist:
print strlist
return ParseList(GetBetweenChar(strlist,'[',None))
else:
return strlist
however it returns:(which although maybe a good start? I dont know where to continue)
[1,[2,2,[3,4]],5]
1,[2,2,[3,4]],5
2,2,[3,4]],
3,4]]
which I would think I would append that to a list item but I dont know how to..
You can use ast.literal_eval to safely convert the string to a nested list of integers. Then define a nested map function to convert to all elements to strings, whilst maintaining the nesting structure.
from ast import literal_eval
s = "[1,[2,2,[3,4]],5]"
ls = literal_eval(s)
# yes I know there is something else called nmap
def nmap(fn, iterable):
res = []
for i in iterable:
if isinstance(i, list): # could be tuple or something else?
res.append(nmap(fn, i))
else:
res.append(fn(i))
return res
result = nmap(str, ls)
print(result)
print(result[1][2][0])
result:
['1', ['2', '2', ['3', '4']], '5']
3
You can use eval(). Just be careful to make sure the string is safe because eval will convert a string to valid python code.
>>> eval("[1,[2,2,[3,4]],5]")[1][2][0]
3
Some more info: What does Python's eval() do?
If you didn't require every piece to be a string, but you could let numbers be numbers, then you can use the json library:
>>> s = "[1,[2,2,[3,4]],5]"
>>> import json
>>> json.loads(s)
[1, [2, 2, [3, 4]], 5]
Notice that if your original list contains numbers or booleans, they will stay as numbers or booleans. This is probably what you want, BUT if you really need everything to be strings, then you can recurse through the nested arrays and apply str to everything (look for "How to do flatmap in Python") or request further help in the comment section below.
You could proceed by first adding the quotes around the digits, then eval the list:
s = "[1,[2,2,[3,4]],5]"
res = ''
for c in s:
if c.isdigit():
res += '"' + c + '"'
else:
res += c
s = eval(res)
s
output:
['1', ['2', '2', ['3', '4']], '5']
This will work for single digit numbers; a little bit more work would be needed for multiple digits, or floats
Eval is not safe for user input.
You can do something like for python (2.6+):
>>> import ast
>>> s = "[1,[2,2,[3,4]],5]"
>>> lst = ast.literal_eval(s)
>>> str(lst[1][2][0])
'3'
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.
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