I know this isn't exactly the first question about list comprehensions, but I've been looking around and experimenting for a while and can't figure this one out. I'll apologize in advance, I'm a self-taught novice learning from failures.
This is working code, but it screams list comprehension. I understand list comprehensions and use them, but the combination of stacking for and working with the dictionaries within the lists is breaking my brain. How would you simplify this:
results = []
for system in systems: # list of dicts
for result in telnet_results: # list of dicts
if system['master_ip'] == result['master_ip']:
combined = {**system, **result} # merge dicts, right takes precedence
results.append(combined)
Thanks in advance for any help on this.
results = [{**system, **result} for system in systems for result in telnet_results if
system['master_ip'] == result['master_ip']]
Can be also splitted more logically:
results = [{**system, **result}
for system in systems
for result in telnet_results
if system['master_ip'] == result['master_ip']]
Is this "simplified"? I'm not sure. List comprehensions are not magic, and they do not always simplify the code or make it more readable.
Related
Any other optimize way to write the below code
t1=[]
for i in range(0,10):
x=int(input())
t1.append(x)
You can go for
t1 = [int(input()) for _ in range(10)]
which does the same thing but does not optimize the code in any meaningful way. While list comprehensions might be faster than for-loops, this doesn't matter when your code has to wait for user input. Furthermore: You probably have to do some input checking/parsing (What happens if the input cannot be cast to an integer?) and this really shouldn't be done inside a list comprehension.
I am trying to find the zig zag pattern between two arrays. I've come across posts where 1 array is used. I understand the logic of it but even when i append the two lists together, I am unable to get the desired output.
arr1 = [1,2,3,4,5]
arr2 = [6,7,8,9,10]
expected_output = [5,9,3,7,1,6,2,8,4,10]
any hint to solve it would help. P.S I am still learning programming, so if i missed an obvious pattern, do let me know. thanks!
I'm currently researching different ways to combine, organize and manipulate data for different purposes.
Just today I found this zip() / iter() technique of creating a LIST containing TUPLES while also being able to specify how many elements are in each TUPLE. However, I'm unable to fully understand part of the syntax.
Here is the code:
mylist = [1,2,3,4,5,6]
converted = [x for x in zip(*[iter(mylist)]*2)]
print(converted)
This is the output (which is what I want):
[(1, 2), (3, 4), (5, 6)]
What I'm trying to grasp is the first asterisk. I understand that it's most likely in relation to the '*2' telling the 'iter' or 'zip' function how many elements each tuple should contain, however, I'm trying to grasp the need for it's placement.
Any help is greatly appreciated.
Also, if you know of another technique to accomplish this and feel like sharing, I'd greatly appreciate learning from you.
Thanks again in advance guys!
Basically iter(mylist) makes an iterator object for the list, then it's put into a list [iter(mylist)] which is multiplied by 2 basically making a list that contains two references to the same iterator object: [iter(mylist)]*2 -> [<list_iterator object at 0x7f8fbc1ac610>, <list_iterator object at 0x7f8fbc1ac610>]
The first asterisk unpacks the list as arguments into the zip() function.
To make it easier to understand as I'm not very good at explaining things, this code does the same as yours:
mylist = [1,2,3,4,5,6]
iterators = [iter(mylist)] * 2
converted = [x for x in zip(*iterators)]
print(converted)
So it makes an iterator, then it makes a list that contains two references to the same iterator object by multiplying it by 2.
And then it unpacks the list to be used as arguments for the zip() function
I hope this cleared it up at least a little for you as I'm not very good at explaining.
I was doing some code from a MIT course and I got this code as a help function, but there are some parts that are a lil obscure from my python
understanding.
def partitions(set_):
if not set_:
yield []
return
for i in range(2**len(set_)//2):
parts = [set(), set()]
for item in set_:
parts[i&1].add(item)
i >>= 1
for b in partitions(parts[1]):
yield [parts[0]]+b
I undrstand that it make lots of different combinations of a list, a dict or other iterating obj.
I got my eyes rolling about this parts:
parts[i&1].add(item)
i >>= 1
Some of the fellows here could try to explain to me this part?
I look for some in the net, but not sure if I understand completly.
Thanks in advance!
PS- There are any way to make a more readble and using biult in functions like permutations, combinations?
I've heard that list comprehensions can be slow sometimes, but I'm not sure why? I'm new to Python (coming from a C# background), and I'd like to know more about when to use a list comprehension versus a for loop. Any ideas, suggestions, advice, or examples? Thanks for all the help.
Use a list comprehension (LC) when it's appropriate.
For example, if you are passing any ol' iterable to a function, a generator expression (genexpr) is often more appropriate, and a LC is wasteful:
"".join([str(n) for n in xrange(10)])
# becomes
"".join(str(n) for n in xrange(10))
Or, if you don't need a full list, a for-loop with a break statement would be your choice. The itertools module also has tools, such as takewhile.