How to select lines and print in a list python
How to select lines and print in a list python
I have a list that looks like this:
1 f
2 f
3 f
4 g
5 g
6 g
and I want to print out the first two lines of f
and g
, as:
f
g
1 f
2 f
4 g
5 g
any idea how to approach this?
Also address some corner cases: what if there is only one "g" item? is the letter column guarenteed to be sorted in order or can you get four 'g's followed by, say, two 'b's?
– gregory
Sep 8 '18 at 3:55
2 Answers
2
You could to consider grouping your list. An example:
l = [['1', 'f'], ['2', 'f'], ['3', 'f'], ['4', 'g'], ['5', 'g'], ['6', 'g']]
To group the list, use a key. In this case, the key would be the second value of each list item, so x[1]
:
x[1]
from itertools import groupby
for _, g in groupby(l, lambda x: x[1]):
print(list(g)[:2])
Slice each group, to only print the first two items, list(g)[:2]
.
list(g)[:2]
Output:
[['1', 'f'], ['2', 'f']]
[['4', 'g'], ['5', 'g']]
Note: this is similar to uniq
in the shell. And it depends or the key values being sorted. You might have to sort the data before using this approach.
uniq
Have added a list of dict, with elem to print along with a count key
Simply increment the value of count to make sure no more than max_limit elements are print.
myList = ['1 f', '2 f', '3 f', '4 g', '5 g', '6 g']
elems_to_print = ['elem': 'f', 'count': 0, 'elem': 'g', 'count': 0]
max_limit = 2
for myL in myList:
for elem in elems_to_print:
if elem['elem'] in myL and elem['count'] < max_limit:
#Elem found
elem['count'] += 1
print("%s"%(myL))
Since SO is not a code writing service, users are discouraged from posting solutions to the questions that do not demonstrate at least some research and effort.
– DYZ
Sep 8 '18 at 3:37
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
A python list cannot look like that. A list must have at least a pair of brackets. Please include the actual list in Python syntax, not a printout. Also, what did you try to solve the problem yourself? Include your code and explain what went wrong.
– DYZ
Sep 8 '18 at 3:34