Making multiple output lists into one list (python) - 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)

Related

resolved Split list into parallel lists using python

I would like to create a parallel list from my original list and then use sort_together
original = ['4,d', '3,b']
parallel list should create 2 lists like this:
lis1 = ['4', '3']
list2 = ['d', 'b']
I've tried using split but was only able to obtain a single list :(
[i.split(",", 1) for i in original]
You can use the zip(*...) trick together with .split:
list1, list2 = zip(*(x.split(",") for x in original))
Now this actually gives you two tuples instead of lists but that should be easy to fix if you really need lists.
You can use map and zip:
lis1, list2 = zip(*map(lambda x:x.split(","), original))
map will apply the function, passed as first argument (in this case, it simply splits strings on the comma separator) to every element of the iterable (list in this case) passed as second argument. After this, you'll have a map object which contains ['4', 'd'] and ['3', 'b']
the zip operator takes two (or more) lists and puts them side by side (like a physical zip would do), creating a lists for elements next to each other. For example, list(zip([1,2,3],[4,5,6])) is [[1.4],[2,5],[3.6]].
The unpacking * is necessary given that you want to pass the two sublists in the returned map object.
ini_list = [[4,'d'], [3,'b']]
print ("initial list", str(ini_list))
res1, res2 = map(list, zip(*ini_list))
print("final lists", res1, "\n", res2)
you can use this code for sort and get two list
list1 , list2 = list(sorted(t) for t in (zip(*(item.split(',') for item in orignal))))
for i in range(2):
s[i] = sorted([oi.split(',')[i] for oi in o])

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)

why sort in python is not working?

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

Converting an integer list into a string list

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"

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