What does this Python syntax do? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
New to python and trying to understand what does following syntax doing ?
def testMissingConfig(self):
""" if config is missing, the config is valid """
input_args = self.buildmock()
validation_errors = [
x
for x in self.validator.validate(
ValidatorArguments(input_args=input_args)
)
if x
]
validation_keys = {x.key for x in validation_errors}
self.assertEmpty(validation_keys)
Especially the array initialization for "validation_errors"

It is called List comprehension. Here you can combine assignments, loops, functions all in one block.
One of the big advantages of list comprehension is that they allow developers to write less
code that is often easier to understand.
Syntax:
[expression for item in list]
Example:
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
Here the numberlist loops over 0 to 20 and gives even numbers 0,2,4...20 as result.
Similarly in your code, validation_errors will store x if x exists(not null)
Lambda functions can also be used to create and modify lists in less lines of code.
Reference:
https://www.programiz.com/python-programming/list-comprehension

Related

List Comprehension starting at a specific number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I was trying to create this [80000, 104000, 135000...] list in Python. Its the value, starting at 80,000 multiplied by 1.3 each time I want
What i've tried:
a = [num*1.5 for num in ??? if num>=80000] #???--> i've tried range(10)
I should be able to do this but I can't find any solutions rn..
I must use list-comprehensions, if possible.
Some help would be nice, thank you!
There is a very basic mathematical operation that represents multiplying by the same value many time: power.
a = [80000 * (1.3**n) for n in range(100)]
You could write your own generator then use that in conjunction with a list comprehension.
def numgen(start, factor, limit):
for _ in range(limit):
yield int(start)
start *= factor
mylist = [value for value in numgen(80_000, 1.3, 10)]
print(mylist)
Output:
[80000, 104000, 135200, 175760, 228488, 297034, 386144, 501988, 652584, 848359]
import numpy as np
print(80000 * 1.3**np.arange(3))
# [ 80000. 104000. 135200.]

How can I add same text to each item of the list? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have the following list:
a=['c1','c2','c3']
And I would like to get to:
b=[sametext['c1'],sametext['c2'],sametext['c3']]
I've tried to make list in list but I'm not able to get any result? How can I get to b?
In [sametext['c1'],sametext['c2'],sametext['c3']], is sametext a dictionary which contains a mapping of some sort?
If that's the case then the way to do it will be with this list comprehension:
b = [sametext[x] for x in a]
Without list comprehensions:
b=[]
for x in a:
b.append(sametext[x])
If by sametext all you mean is some constant operation, like adding a prefix then similar to the first approach the way would be:
b = [f"yourprefix_{x}]" for x in a]
b= [ele+'some_text' for ele in a]
To make change in-place
a[:] = [ele+'some_text' for ele in a]

How do I return a list of numbers below a certain threshold without using complex list functions? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I can't figure out how to do this without using complex functions, please help. this is the docstring of the code:
'''
finds all numbers in the list below a certain threshold
:param numList: a list of numbers
:threshold: the cutoff (only numbers below this will be included)
:returns: a new list of all numbers from numList below the threshold
'''
One approach
def filterList(numList, threshold):
return list(filter(lambda x: x < threshold, numList))
Another approach:
filteredList = [x for x in numList if x < threshold]

Printing and array two times in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a list a=['abc','cdv','fasdf'] and also have a constant n which says the amount of time print each elements two times.
For example, n=2 should return a=['abc','abc','cdv','cdv']; or n=4 will return a=['abc','abc','cdv','cdv','fasdf','fasdf','abc','abc'].
Here is one way using itertools.chain and a generator comprehension:
from itertools import chain
a = ['abc','cdv','fasdf']
n = 4
res = list(chain.from_iterable([a[i % len(a)]]*2 for i in range(n)))
# ['abc', 'abc', 'cdv', 'cdv', 'fasdf', 'fasdf', 'abc', 'abc']
it looks like you'll need to recycle elements if n is larger than the length of the list. An easy way to deal with this is to duplicated the array as many times as needed.
import math
n_over = math.ceil(len(a)/n)
n_reps = 1 + n_over
a_long = a * n_reps
we can iterate over the new array to build the new one
a_rep = []
for e in a_long[0:n]:
a_new += [e]*n

reversed() vs. xrange() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to traverse a list backwards. I read about xrange() and reversed(). Which one is more expensive?
You can use Python's timeit library to time things like this. You don't say what kind of list you have, so I am assuming a simple list of strings. First I create a list 100 items long and then time both:
my_list = ["hello"] * 100
def v1():
for x in my_list[::-1]:
pass
def v2():
for x in reversed(my_list):
pass
print timeit.timeit(v1)
print timeit.timeit(v2)
This gives the following result:
2.78170533583
2.13084949985
As you can see, in this example reversed() is a bit faster.
xrange() produces a sequence of numbers. You can then use those numbers as list indices if you want, or you can use them for anything where you want those numbers.
for i in xrange( len(l)-1, -1, -1):
item = l[i]
print item
reversed() produces the items from something that has a length and can be indexed.
for item in reversed(l):
print item
I would use reversed() because it makes you code shorter, simpler, clearer, and easier to write correctly.

Categories