List comprehension example I don't understand [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 4 years ago.
Improve this question
I'm having trouble understanding a particular list comprehension example. In the sample code below a list comprehension is used for the parameter of the set method. Most examples I've seen usually look like this "x for x in y". I've read documentation but it isn't clearing it up for me. What exactly is [marks for name] doing. Shouldn't it be [marks for marks]?
marksheet = []
for _ in range(0,int(input())):
marksheet.append([input(), float(input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

Your code is using Python's list comprehension to create a list from another list based on the condition.
See more about list comprehensions here:
https://www.programiz.com/python-programming/list-comprehension
The [1] is accessing the item at index 1 (2nd item) of your sorted list.
As for .join, each line in the sorted list is being printed out with a newline (\n) between each one.

Related

Is there a python function that can sort a list based on capital letters? [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 a list such that:
['DYLAN','BOB','ROB']
Everything is capitalized, so I have written some python code that takes the first letter and then sorts it alphabetically, but I am wondering now if I can do it with a python function. Thank you.
The case of the list does not matter when sorting. What you want could be found here. In regards to converting to lower case, you can use list comprehension to convert all values of the list to lower case: [c.lower() for c in yourlist]. To learn more about list comprehension, I suggest you look here. Cheers
list has a sort() function:
l = ['DYLAN','BOB','ROB']
l.sort()
print(l)
['BOB', 'DYLAN', 'ROB']
Besides .sort() which was already mentioned in another answer, you can also use sorted() like such:
sorted(["DYLAN", "BOB", "ROB"])

simplify for loop and if statement with list comprehension [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 2 years ago.
Improve this question
I am looking to simplify the below with list comprehension:
for contract in response:
if contract['symbol'] == symbol:
price = contract['lastPrice']
I have come up with:
[contract for contract in response if contract['symbol'] == symbol]:
price = contract['lastPrice']
But I am not sure with this syntax is not correct.
Here you go;
price = [contract["lastPrice"] for contract in response if contract["symbol"] == symbol]
print(price)
Comprehensions are not compound block of code in python but simply expressions which define a particular for loop in a single line of code. As your question is regarding list comprehension, list comprehension is a way of expressing a lop (with or without some condition) in the form of an expression which returns a list as result.
You can also get a dict() as result by using dictionary comprehension.
EDIT:
If this is answer to your question, mark this as accepted. Thanks!

Recursively append over nested list python [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 am trying to recursively append to a list while iterating over a nested list. For example, if I have a list [['a',['b',['c','d']]]], I would like a function to return [['a','b','c'],['a','b','d']]. My attempt so far is the following:
def recurse_append(data):
r_list=[]
for elem in data:
if isinstance(elem, list):
r_list.extend(recurse_append(elem))
else:
r_list.append(elem)
return r_list
which for this example returns ['a','b','c','d']. Unlike the example, the nested list that I am writing this for does not contain the same number of elements at each level, so I thought that a recursive function would be the best way to take this into account. Any help towards a solution would be greatly appreciated.

How do I make this snippet Pythonic? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I want to know how Python programmers would write the following snippet:
for i in range(10):
indexVector[i] = empAvg[i] + upperBound(t, pullCount[i])
Here t is a constant. As you can see, I am used to C/C++ style code but want to use Python the right way.
You can zip the lists empAvg and pullCount to iterate through them element-wise without the need for the i counter, then use a list comprehension to create indexVector
indexVector = [emp + upperBound(t, pull) for emp, pull in zip(empAvg, pullCount)]
If you want to use list comprehension to create indexVector (assuming it does not have any other value outside the 10 indexes that you entered in your snippet) , you can use -
indexVector = [empAvg[i] + upperBound(t, pullCount[i]) for i in range(10)]

using split for appending to multiple lists [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 9 years ago.
Improve this question
Is it possible to combine the two statements inside 'for' loop.
num_pro=raw_input("ENTER THE NUMBER OF PRODUCTIONS: ")
right=[];left=[];
for i in range(int(num_pro)):
l,r=raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->')
right.append(r);left.append(l)
sample input: E->abc
Append tuples to one list, then split out the lists using zip():
entries = []
for i in range(int(num_pro)):
entries.append(raw_input("ENTER PRODUCTION"+str(i+1)+" : ").split('->'))
left, right = zip(*entries)
zip(*iterable) transposes the nested list; columns become rows. Because you have two 'columns' (pairs of values), you end up with two rows instead.
Not without making it more complex. Each method needs to be called individually, and the only way to do that is either explicitly, as you have done, or in a loop.
If you are willing to store the whole production (which isn't necessarily a bad idea, since it keeps both sides synchronized) then just append the split result instead.
productions = []
for ...
productions.append(....split('->'))

Categories