This question already has answers here:
Outerzip / zip longest function (with multiple fill values)
(3 answers)
Closed 5 years ago.
I need to zip two lists inclusively. I.e. keep values of the longer list and, possibly, add a default value for the shorter one:
e.g.
lst_a = [1,2,3] # len = 3
lst_b = [5,6,7,8] # len = 4
# no default values
inclusive_zip(lst_a, lst_b) = [(1,5),(5,6),(3,7),(None,8)]
# with default value (e.g. for position in 2D space)
inclusive_zip(lst_a, 0, lst_b, 0) = [(1,5),(5,6),(3,7),(0,8)]
I can make something of my own, but was wondering if there's a built-in or super simple solution.
itertools.zip_longest(*iterables, fillvalue=None)
import itertools
def add_by_zip(p1,p2):
p_out = [a+b for a,b in itertools.zip_longest(p1,p2, fillvalue=0)]
print(p_out)
Related
This question already has answers here:
Python "for i in" + variable
(3 answers)
Closed 2 years ago.
I'm trying to return a list of odd numbers below 15 by using a python user-defined function
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(15))
But I'm getting this error :
TypeError: 'int' object is not iterable
I didn't understand what exactly this means, please help me find my mistake
Because 15 is an integer, not a list you need to send the list as an input something like range(0,15) which will give all numbers between 0 and 15.
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(range(0,15)))
When you're passing values to the function oddnos, you're not passing a list of values till 15, rather only number 15. So the error tells you, you're passing an int and not a list, hence not iterable.
Try to use range() function directly in the for loop, pass your number limit to the oddnos function.
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.
I tried using the sort method but doesn;t work
>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>
Am i missing anything here .. kindly clarify
I want the output in the following format
1/1/6 1/1/11
Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ..., so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11 is one element of a sequence and not two).
List b contains a transformed list, where each element is a tuple. And now sort will work as you want.
The second option, will be using a custom key operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple of integers and will be compared as you want.
Note 1
The second approach (with the key operator) will create an additional overhead during sorting as it will be called O(NlogN) times.
Note 2
You also tried using the result of sort function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.
I have a list:
a = [[1,2,3],[4,5,6],[7,8,9]]
And I want the average of the 3rd element of each list: (3 + 6 + 9)
Which function should i create in order to do this??
It is always better to let others know what you have tried yourself when asking questions on Stackoverflow.
Anyway, try the below code:
def third_avg(a_list):
list_of_third = [i[2] for i in a_list]
return sum(list_of_third)/len(list_of_third)
print(third_avg([[1,2,3],[4,5,6],[7,8,9]]))
Output:
6.0
This function basically creates a new list with only the third values of the sublists. Then returns the average (sum of all elements/num of elements).
This question already has answers here:
How are Python in-place operator functions different than the standard operator functions?
(2 answers)
Closed 6 years ago.
I'm trying to update a multiplicative value to a variable.
I know that I can do += and -= for addition and subtraction and *= for multiplication, but I don't fully grasp the entirety of that type of operation. Can someone point me to the documentation that covers this? I can't seem to find it on python.org.
Well technically you are never updating python variables (integers, strings and floats among many other are immutable), you are re-assigning a value to a name.
+ is shorthand for add(), * is shorthand for mul() and - is short for sub().
since you are re-assigning variable, you are essentially performing these operations (when adding, substracting, multiplying, dividing or whatever it is that you do):
a = 1
a = a + 1 # a = 2
a = a * 2 # a = 4
a = a - 1 # a = 3
+=, -= and *= are just shorts for the above expressions.
i.e. the above can be restated as:
a = 1
a += 1
a *= 2
a -= 1
python docs for operators: https://docs.python.org/3.5/library/operator.html
see also python docs for inplace operators for more information: https://docs.python.org/3.5/library/operator.html#inplace-operators
This question already has answers here:
Generate a matrix containing all combinations of elements taken from n vectors
(4 answers)
Closed 7 years ago.
I have the letters "A", "B", "C", "D", and "E" and I want to generate all possible strings of length 7 with these letters (redundancy allowed). So, I would like to get:
AAAAAAA
AAAAAAB
AAAAAAC
AAAAAAD
AAAAAAE
...
So on and so forth with all possible strings. I know how to do this manually via the following, create:
A = ['A'], B = ['B'], etc...then create embedded for loops to concatenate all elements. However, I would like to just feed in a generic list of ABCDE in a function, and just feed the function an integer to get a variable result. How could I do this?
Something like this?
Test = 'ABCDE';
A = cell(7, 1); %//pre-allocating for speed
[A{:}] = ndgrid(Test);
y = cellfun(#(Test) {Test(:)} , A);
y = horzcat (y{:});
>>
AAAAAAA
BAAAAAA
CAAAAAA
DAAAAAA
EDIT: ops... didn't see the 7..