Python extract list of unknow length - python

I have a string from user. It must containt a comma to split by it and assign to variables. But what if user miss a comma? Surely I can check len of splitted string in if-else branches, but maybe there is another way, I mean assignment during list has a values. For example
a, b, c, d, e = list(range(3)) # 'a' and 'b' are None or not exists

You could do something like this:
>>> alist=list(range(3))
>>> alist
[0, 1, 2]
>>> a,b,c,*d=alist
>>> a,b,c
(0, 1, 2)
>>> d
[]
If there are no more elements, d is an empty list. It uses the unpacking operator *. Not the best possible solution for large lists, so I would still define a function for that. For small cases, it works well. (You could assume that is d==[], there are no more elements in alist)For example, you could add:
return False if not d else return True

You are free to extend the list with None values before extraction.
li = list(range(3))
expected_size = 5
missing_size = expected_size - len(li)
none_li = [None] * missing_size
new_li = li + none_li
a, b, c, d, e = new_li

Related

List comprehension from two sources

Having this input:
a = (1,2,3)
b = 'something'
I want to create a list which will look like that:
['something', 1, 2, 3]
I tried to do:
[b, i for i in a]
But got a syntax error.
Note that, I'm looking for a one line solution out of curiosity.
If your variable 'a' will always be a tuple and 'b' will always be a string then you can try one thing...
a = (1,2,3)
b = 'something'
c = [b] + [i for i in a]

Opposite of set.intersection in python?

In Python you can use a.intersection(b) to find the items common to both sets.
Is there a way to do the disjoint opposite version of this? Items that are not common to both a and b; the unique items in a unioned with the unique items in b?
You are looking for the symmetric difference; all elements that appear only in set a or in set b, but not both:
a.symmetric_difference(b)
From the set.symmetric_difference() method documentation:
Return a new set with elements in either the set or other but not both.
You can use the ^ operator too, if both a and b are sets:
a ^ b
while set.symmetric_difference() takes any iterable for the other argument.
The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets.
a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}
The best way is a list comprehension.
a = [ 1,2,3,4]
b = [ 8,7,9,2,1]
c = [ element for element in a if element not in b]
d = [ element for element in b if element not in a]
print(c)
# output is [ 3,4]
print(d)
# output is [8,7,9]
You can join both lists
Try this code for (set(a) - intersection(a&b))
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
the output is [1,4,5,6]
I hope, it will work
e, f are two list you want to check disjoint
a = [1,2,3,4]
b = [8,7,9,2,1]
c = []
def loop_to_check(e,f):
for i in range(len(e)):
if e[i] not in f:
c.append(e[i])
loop_to_check(a,b)
loop_to_check(b,a)
print(c)
## output is [3,4,8,7,9]
This loops around to list and returns the disjoint list

Map the max function for list of the lists

I stack with the following problem, I need to finding maximum between equal positions between lists. Map function works pretty well, but how to make it work for the list of the lists? using map(max,d) gave the max of the every list. The problem is that the number of the lists in the list is variable. Any suggestions are welcome!
Input for the problem is d not an a,b,c, d - is a list of the lists, and the comparison is pairwise per position in the list.
a = [0,1,2,6]
b = [5,1,0,7]
c = [3,8,0,8]
map(max,a,b,c)
# [5,8,2,8]
d = [a,b,c]
map(max,d)
[6,7,8]
a = [0,1,2,6]
b = [5,1,0,7]
c = [3,8,0,8]
print [max(itm) for itm in zip(a, b, c)]
or even shorter:
print map(max, zip(a, b, c))
How about this:
max(map(max,d))

How to copy data in Python

After entering a command I am given data, that I then transform into a list. Once transformed into a list, how do I copy ALL of the data from that list [A], and save it - so when I enter a command and am given a second list of data [B], I can compare the two; and have data that is the same from the two lists cancel out - so what is not similar between [A] & [B] is output. For example...
List [A]
1
2
3
List [B]
1
2
3
4
Using Python, I now want to compare the two lists to each other, and then output the differences.
Output = 4
Hopefully this makes sense!
You can use set operations.
a = [1,2,3]
b = [1,2,3,4]
print set(b) - set(a)
to output the data in list format you can use the following print statement
print list(set(b) - set(a))
>>> b=[1,2,3,4]
>>> a=[1,2,3]
>>> [x for x in b if x not in a]
[4]
for element in b:
if element in a:
a.remove(element)
This answer will return a list not a set, and should take duplicates into account. That way [1,2,1] - [1,2] returns [1] not [].
Try itertools.izip_longest
import itertools
a = [1,2,3]
b = [1,2,3,4]
[y for x, y in itertools.izip_longest(a, b) if x != y]
# [4]
You could easily modify this further to return a duple for each difference, where the first item in the duple is the position in b and the second item is the value.
[(i, pair[1]) for i, pair in enumerate(itertools.izip_longest(a, b)) if pair[0] != pair[1]]
# [(3, 4)]
For entering the data use a loop:
def enterList():
result = []
while True:
value = raw_input()
if value:
result.append(value)
else:
return result
A = enterList()
B = enterList()
For comparing you can use zip to build pairs and compare each of them:
for a, b in zip(A, B):
if a != b:
print a, "!=", b
This will truncate the comparison at the length of the shorter list; use the solution in another answer given here using itertools.izip_longest() to handle that.

python - match on array return value

I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.
For example, assume that perms(x) returns a list of values, and I want to do this:
seq=perms(x)
a = seq[0]
b = seq[1]
rest = seq[2:]
Of course I can shorten to:
[a,b] = seq[0:2]
rest = seq[2:]
Can I use some notation to do this?
[a,b,more] = perms(x)
or conceptually:
[a,b,more..] = perms(x)
PROLOG & functional languages do list decomposition so nicely like this!
You can do it in Python 3 like this:
(a, b, *rest) = seq
See the extended iterable unpacking PEP for more details.
In python 2, your question is very close to an answer already:
a, b, more = (seq[0], seq[1], seq[2:])
or:
(a, b), more = (seq[0:2], seq[2:])
For Python 2, I know you can do it with a function:
>>> def getValues(a, b, *more):
return a, b, more
>>> seq = [1,2,3,4,5]
>>> a, b, more = getValues(*seq)
>>> a
1
>>> b
2
>>> more
(3, 4, 5)
But not sure if there's any way of doing it like Ayman's Python 3 suggestion
Very nice, thanks.
The suggestions where one dissects the array on the fight-hand side don't work so well for me, as I actually wanted to pattern match on the returns from a generator expression.
for (a, b, more) in perms(seq): ...
I like the P3 solution, but have to wait for Komodo to support it!

Categories

Resources