Converting an integer list into a string list - python

I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234

You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map():
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join():
>>> ''.join(str_list)
'1234'
And please don't name your list list. It shadows the built-in list.

>>>l=[1,2,3,4]
I've modified your example to not use the name list -- it shadows the actual builtin list, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)

Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234

l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"

Related

Vector convert from txt file in Python [duplicate]

How do I convert all strings in a list to integers?
['1', '2', '3'] ⟶ [1, 2, 3]
Given:
xs = ['1', '2', '3']
Use map then list to obtain a list of integers:
list(map(int, xs))
In Python 2, list was unnecessary since map returned a list:
map(int, xs)
Use a list comprehension on the list xs:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
There are several methods to convert string numbers in a list to integers.
In Python 2.x you can use the map function:
>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]
Here, It returns the list of elements after applying the function.
In Python 3.x you can use the same map
>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]
Unlike python 2.x, Here map function will return map object i.e. iterator which will yield the result(values) one by one that's the reason further we need to add a function named as list which will be applied to all the iterable items.
Refer to the image below for the return value of the map function and it's type in the case of python 3.x
The third method which is common for both python 2.x and python 3.x i.e List Comprehensions
>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
You can easily convert string list items into int items using loop shorthand in python
Say you have a string result = ['1','2','3']
Just do,
result = [int(item) for item in result]
print(result)
It'll give you output like
[1,2,3]
If your list contains pure integer strings, the accepted answer is the way to go. It will crash if you give it things that are not integers.
So: if you have data that may contain ints, possibly floats or other things as well - you can leverage your own function with errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
Output:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
To also handle iterables inside iterables you can use this helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
Output:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
A little bit more expanded than list comprehension but likewise useful:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
e.g.
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Also:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
Here is a simple solution with explanation for your query.
a=['1','2','3','4','5'] #The integer represented as a string in this list
b=[] #Fresh list
for i in a: #Declaring variable (i) as an item in the list (a).
b.append(int(i)) #Look below for explanation
print(b)
Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).
Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.
Output console:
[1, 2, 3, 4, 5]
So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("").
I also want to add Python | Converting all strings in list to integers
Method #1 : Naive Method
# Python3 code to demonstrate
# converting list of strings to int
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #2 : Using list comprehension
# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(i) for i in test_list]
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
Method #3 : Using map()
# Python3 code to demonstrate
# converting list of strings to int
# using map()
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using map() to
# perform conversion
test_list = list(map(int, test_list))
# Printing modified list
print ("Modified list is : " + str(test_list))
Output:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
The answers below, even the most popular ones, do not work for all situations. I have such a solution for super resistant thrust str.
I had such a thing:
AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']
AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA
[0.0, 0.5, 0.5, 0.1, 0.1, 0.1, 0.1]
You can laugh, but it works.

Python - Return true if strings found in nested list

My goal is to return True/False if I am able to detect two items within a nested list.
E.g.
list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]
I want to iterate over this list to confirm if I can find '1' & 'MSG1' within a nested list. Important to note I only want this to return true if both items are found and if they're found within the same nested list.
I've tried various combinations of the below however I cannot get it quite right.
all(x in e for e in list1 for x in ['1', 'MSG1'])
Any assistance is greatly appreciated.
Try this:
contains = any([True for sublist in list1 if "1" in sublist and "MSG1" in sublist])
You can use set.issubset:
any(True for sub_list in list1 if {'1', 'MSG1'}.issubset(set(sub_list)))
You need to apply all to each test of 1 and MSG being in list1, so you need to rewrite your list comprehension as
found = [all(x in e for x in ['1', 'MSG1']) for e in list1]
# [True, False, False]
You can then test for any of those values being true:
any(found)
# True
You can make a function as follows, using sum and list's count method:
def str_in_nested(list_, string_1, string_2):
return sum(sub_list.count(string_1) and sub_list.count(string_2) for sub_list in list_) > 0
Applying this function to you current case:
>>> list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]
>>> str_in_nested(list1, '1', 'MSG1')
True
It's:
any(all(item in sublist for item in ['1', 'MSG1']) for sublist in list1)
Give this a try...
for item in list1:
all(i in item for i in sub)

Making multiple output lists into one list (python)

I have this generator
def keys():
objects = [{'1':True,'2':True,'3':False,'4':False,'5':True,'6':True}]
rng = range(len(objects))
clean = int(''.join(map(str, rng)))
for keys, values in objects[clean].iteritems():
if values == True:
yield keys
and then i want to get all the generator values, which I do using for loop
for i in keys():
i= i.split()
print i
and the output is :
['1']
['2']
['5']
['6']
is there a way I can add them to a single list?
like [['1'],['2'],['5'],['6']] or most preferably ['1','2','5','6'].
Would greatly appreciate your help. Thanks
You can just convert it to a list directly, as list takes an iterable;
out = list(keys())
Or if you want to, you could use a list comprehension;
out = [key for key in keys()]
This would make it easier to filter out certain items from the generator using the [for x in y if z] syntax.
Both output;
>>> print(out)
['2', '6', '1', '5']
Like this?:
my_list = []
for i in keys():
my_list.append(i.split())
print my_list
It would be a list comprehension like this if you want it as similar as possible to your original answer:
list = [key.split() for key in keys()]
print(list)

Taking Elements From a List

I want to take an element of a list and remove the final character. The overall aim being to convert the number remaining from str to int for an equation. I thought this:
hand = ['1D', '5S', '10H']
first_card = hand [0]
first_card [:-1]
print [first_card]
...was the way to do so, but apparently not.
Thanks in advance for any help provided.
Frazer
This can be accomplished for all elements with a list comprehension.
>>> hand = ['1D', '5S', '10H']
>>> hand2 = [i[:-1] for i in hand]
>>> hand2
['1', '5', '10']
You can also easily convert this to ints at the same time:
>>> handints = [int(i[:-1]) for i in hand]
>>> handints
[1, 5, 10]
In case if the string contains multiple characters towards the ending.
from itertools import takewhile
map(lambda x: "".join(list(takewhile(lambda x: x.isdigit(),x))), ['1D', '5S', '10H'])
Or using a list comprehension
[int("".join(list(takewhile(lambda x: x.isdigit(),x)))) for x in ['1D', '5S', '10H']]
use map to solve trivial operations on every element in a list:
list(map(lambda x: x[:-1],hand))

Difference between list of lists

I have two lists
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
I want to perform A-B operation on these comparing only first element.
so A-B should give
Output=[['3', '2']]
So far, I could do only on row comparison
[x for x in A if not x in B]
which gives output as [['2', '1'], ['3', '2']]
This?
>>> [i for i in A if not any(i[0] == k for k, _ in B)]
[['3', '2']]
any() is used to check if the first element of each list is the same as any other value in every list in B. If it is, it returns True, but as we want the opposite of this, we use not any(...)
You can also use collections.OrderedDict and set difference here:
>>> from collections import OrderedDict
>>> dic1 = OrderedDict((k[0],k) for k in A)
>>> [dic1[x] for x in set(dic1) - set(y[0] for y in B)]
[['3', '2']]
Overall complexity is going to be O(max(len(A), len(B)))
If order doesn't matter then a normal dict is sufficient.
I could think of a different list comprehension
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b]
This is order preserving as well and can work even if there are duplicate fist elements in the inner list of A. Also it can be extended to check for exact pair if needed like this:
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b or b[item[0]] != item[1]]

Categories