This question already has answers here:
how to change [1,2,3,4] to '1234' using python
(2 answers)
Closed 7 years ago.
I'm a Python beginner struggling to write code that uses the list myList = [['A','B','C'],[4,5,6],[7,8,9]] and generates the output below:
Input:
myList = [['A','B','C'],[4,5,6],[7,8,9]]
Expected output: (by line)
-A-B-C-
-4-5-6-
-7-8-9-
I've tried a few different things but am not sure how to approach the confluence of strings and integers in the same list.
I can get:
>>> for i in range (0,myList_len):
... print ("-".join(myList[i]))
...
A-B-C
But I can't get this to work for the numbers. Any help would be much appreciated!
You could use map to convert from int to str
for l1 in myList:
print '-' + '-'.join(map(str, l1)) + '-'
When you try to join numbers, you get the following error:
TypeError: sequence item 0: expected str instance, int found
This is because str.join() only works with str items in the iterable, but you pass it int objects instead.
So in order to properly join them, you need to convert them to strings first. You can either do that by calling str on every item using map, or by using a list comprehension:
>>> lst = [4, 5, 6]
>>> '-'.join(map(str, lst))
'4-5-6'
>>> '-'.join([str(x) for x in lst])
'4-5-6'
The "join" operator expects a list of strings, so you have to turn your numbers to strings first, using the "str" operator that turns anything into a string.
for l in myList:
print '-' + '-'.join([str(x) for x in l]) + '-'
join works on strings, not numbers. You need to convert:
print ("-".join(str(num) for num in myList[i]))
Now, just add the hyphens at start and finish, and you're done.
Try the following:
for sublist in myList:
print("-".join(map(str, sublist)))
The output is:
A-B-C
4-5-6
7-8-9
If you want leading and trailing hyphens as well, use:
for sublist in myList:
print("-" + "-".join(map(str, sublist)) + "-")
The output is:
-A-B-C-
-4-5-6-
-7-8-9-
The for loop iterates over the sublists. The map(str, sublist) call applies str to each element of the sublist, converting it to a string. Without this, your non-string entries (i.e., numbers) were causing errors when passed to join.
Related
This question already has answers here:
How to convert a string of space- and comma- separated numbers into a list of int? [duplicate]
(6 answers)
Closed 18 days ago.
I have this:
"1,2,3,4,5,6,7,8,9,0"
And need this:
[1,2,3,4,5,6,7,8,9,0]
Everything I search for has the example where the string is a list of strings like this:
"'1','2','3'..."
those solutions do not work for the conversion I need.
What do I need to do? I need the easiest solution to understand for a beginner.
You could use a mapping to convert each element to an integer, and convert the map to a list:
s = "1,2,3,4,5,6,7,8,9,0"
l = list(map(int, s.split(',')))
print(l)
You can use str.split to get a list, then use a list comprehension to convert each element to int.
s = "1,2,3,4,5,6,7,8,9,0"
l = [int(x) for x in s.split(",")]
print(l)
You can just call int("5") and you get 5 like a int.
In your case you can try list comprehension expression
a = "1,2,3,4,5,6,7,8,9,0"
b = [int(i) for i in a.split(',')]
print(b)
>> 1,2,3,4,5,6,7,8,9,0
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I have a problem with sort. Want to sort the list like
['asd_1qwer', 'asd_14qwer', 'asd_26qwer', 'asd_5qwer']
I found out that i need to add zeros to 1 and 5.
['asd_01qwer', 'asd_05qwer', 'asd_14qwer', 'asd_26qwer']
Dont know how to add it to right position because asd is not static.
list = ['asd_14qwer','asd_5qwer','asd_26qwer','asd_1qwer']
list.sort()
for i in list:
tempo = i.split('_')[-1].split('qwer')[0]
if len(tempo) == 1:
i[:4] + '0' + i[4:]
Edit
Need to add 0 to 1-9 and qwer list constant over all labels.
Actually, if your goal is to sort the list according to the numerical part of the strings, you don't need to zero-pad these numerical part, you just need to provide key function to sort() that extracts the numeric part as an integer:
l = ['asd_14qwer','asd_5qwer','asd_26qwer','asd_1qwer']
l.sort(key=lambda x: int(x.split('_')[-1].rstrip('qwer')))
Please note that this code does not depend on the characters preceding _, only on the fact that the numerical part is between _ and qwer.
You can sort also without adding zeros:
list = ['asd_14qwer','asd_5qwer','asd_26qwer','asd_1qwer']
list.sort(key=lambda i: int(i[(i.index('_') + 1):-4]))
print(list)
Output:
['asd_1qwer', 'asd_5qwer', 'asd_14qwer', 'asd_26qwer']
you can use:
my_list.sort(key=lambda x: int(x[4:][:-4]))
or you can use a regular expression:
import re
my_list.sort(key=lambda x: int(re.search(r'\d+', x).group()))
for i in range(len(list)):
if len(list[i])==9:
list[i] = list[i][:4]+'0'+list[i][4:]
This will add the zeroes at the required places in the list
a 'natural sort' perhaps
import re
def natsort(lst):
"""natural sort"""
lst = [str(i) for i in lst]
import re
convert = lambda text: int(text) if text.isdigit() else text
a_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(lst, key=a_key)
lst = ['asd_1qwer', 'asd_14qwer', 'asd_26qwer', 'asd_5qwer']
natsort(lst)
Out[3]: ['asd_1qwer', 'asd_5qwer', 'asd_14qwer', 'asd_26qwer']
Please don't shadow build-in names. I renamed list to my_list below. :)
Also, based on your answers in the comments, your approach was mostly correct, but you don't need to add padding 0 if you're sorting with only numbers - you just need to parse that part as a number! No matter the length - 3, 21, or 111, it will sort correctly then.
sort function has a parameter key where you can set what should be used to sort the elements in the list - that's where we need to put our snippet that extracts and parses the number:
my_list = ['asd_14qwer','asd_5qwer','asd_26qwer','asd_1qwer']
my_list.sort(key=lambda word: int(word.split('_')[-1].split('qwer')[0]))
As you can see, the snippet is similar to what you tried - I just wrapped it in the int call. :)
Result:
['asd_1qwer', 'asd_5qwer', 'asd_14qwer', 'asd_26qwer']
This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 3 years ago.
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.
By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.
list1=["-7","-7","-6"]
for test in list1:
test=int(test)
print( type( list1[0] ) )
I expected type to be int but output is coming as str instead.
You need to modify the content of the list:
list1=["-7","-7","-6"]
for i in range(len(list1)):
list1[i] = int(list1[i])
print(type(list1[0]))
A more pythonic approach would be to use a comprehension to change it all at once:
list1 = [int(x) for x in list1]
Try this to convert each item of a list to integer format :
list1=["-7","-7","-6"]
list1 = list(map(int, list1))
list1 becomes [-7, -7, -6].
Now type(list1[0]) would be <class 'int'>
You forgot about appending the transformed value:
list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
test = int(test)
list2.append(test) # store transformed values
print(type(list2[0]))
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.
Actually quite simple question:
I've a python list like:
['1','2','3','4']
Just wondering how can I strip those single quotes?
I want [1,2,3,4]
Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:
map(int, your_list)
and
[int(value) for value in your_list]
See the documentation on map() and list comprehensions for more info.
If you want to leave the items in your list as strings but display them without the single quotes, you can use the following:
print('[' + ', '.join(your_list) + ']')
If that's an actual python list, and you want ints instead of strings, you can just:
map(int, ['1','2','3','4'])
or
[int(x) for x in ['1','2','3','4']]
Try this
[int(x) for x in ['1','2','3','4']]
[1, 2, 3, 4]
and to play safe you may try
[int(x) if type(x) is str else None for x in ['1','2','3','4']]