I have the list_of_lists and I need to get the string that contains 'height' in the sublists and if there is no height at all I need to get 'nvt' for the whole sublist.
I have tried the following:
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
_lists = []
for list in list_of_lists:
list1 = []
for st in list:
if ("height" ) in st:
list1.append(st)
else:
list1.append('nvt')
_lists.append(list1)
OUT = _lists
the result I need to have is :
_lists = ['nvt', 'height=4']
what I'm getting is:
_lists = [['nvt','nvt'],['nvt','nvt','height=4']]
This is a good case for implementing a for/else construct as follows:
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
result = []
for e in list_of_lists:
for ss in e:
if ss.startswith('height'):
result.append(ss)
break
else:
result.append('nvt')
print(result)
Output:
['nvt', 'height=4']
Note:
This could probably be done with a list comprehension but I think this is more obvious and probably has no significant difference in terms of performance
This should work, you can assign height variable to first value in the sublist where s.startswith("height") is True, and if nothing matches this filter, you can assign height to 'nvt'.
_lists = []
for sublist in list_of_lists:
height = next(filter(lambda s: s.startswith("height"), sublist), 'nvt')
_lists.append(height)
And if you wish to be crazy, you can use list comprehension to reduce the code to the:
_lists = [next(filter(lambda s: s.startswith("height"), sublist), 'nvt') for sublist in list_of_lists]
Try this (Python 3.x):
import re
list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]
_lists = []
r = re.compile("height=")
for li in list_of_lists:
match = list(filter(r.match, li))
if len(match) > 0:
_lists.extend(match)
else:
_lists.append('nvt')
OUT = _lists
print(OUT)
Related
I have a list:
List1 = ['name','is','JOHN','My']
I want to append the pronoun as the first item in a new list and append the names at last. Other items should be in the middle and their positions can change.
So far I have written:
my_list = ['name','is','JOHN','My']
new_list = []
for i in my_list:
if i.isupper():
my_list.remove(i)
new_list.append(i)
print(new_list)
Here, I can't check if an item is completely upper case or only its first letter is upper case.
Output I get:
['name','is','JOHN','My']
Output I want:
['My','name','is','JOHN']
or:
['My','is','name','JOHN']
EDIT: I have seen this post and it doesn’t have answers to my question.
i.isupper() will tell you if it's all uppercase.
To test if just the first character is uppercase and the rest lowercase, you can use i.istitle()
To make your final result, you can append to different lists based on the conditions.
all_cap = []
init_cap = []
non_cap = []
for i in my_list:
if i.isupper():
all_cap.append(i)
elif i.istitle():
init_cap.append(i)
else:
non_cap.append(i)
new_list = init_cap + non_cap + all_cap
print(new_list)
DEMO
How about this:
s = ['name', 'is', 'JOHN', 'My']
pronoun = ''
name = ''
for i in s:
if i.isupper():
name = i
if i.istitle():
pronoun = i
result = [pronoun, s[0], s[1], name]
print(result)
Don't # me pls XD. Try this.
my_list = ['name','is','JOHN','My']
new_list = ['']
for i in range(len(my_list)):
if my_list[i][0].isupper() and my_list[i][1].islower():
new_list[0] = my_list[i]
elif my_list[i].islower():
new_list.append(my_list[i])
elif my_list[i].isupper():
new_list.append(my_list[i])
print(new_list)
I have a list of strings:
a = ['book','book','cards','book','foo','foo','computer']
I want to return anything in this list that's x > 2
Final output:
a = ['book','book','book']
I'm not quite sure how to approach this. But here's two methods I had in mind:
Approach One:
I've created a dictionary to count the number of times an item appears:
a = ['book','book','cards','book','foo','foo','computer']
import collections
def update_item_counts(item_counts, itemset):
for a in itemset:
item_counts[a] +=1
test = defaultdict(int)
update_item_counts(test, a)
print(test)
Out: defaultdict(<class 'int'>, {'book': 3, 'cards': 1, 'foo': 2, 'computer': 1})
I want to filter out the list with this dictionary but I'm not sure how to do that.
Approach two:
I tried to write a list comprehension but it doesn't seem to work:
res = [k for k in a if a.count > 2 in k]
A very barebone answer is that you should replace a.count by a.count(k) in your second solution.
Although, do not attempt to use list.count for this, as this will traverse the list for each item. Instead count occurences first with collections.Counter. This has the advantage of traversing the list only once.
from collections import Counter
from itertools import repeat
a = ['book','book','cards','book','foo','foo','computer']
count = Counter(a)
output = [word for item, n in count.items() if n > 2 for word in repeat(item, n)]
print(output) # ['book', 'book', 'book']
Note that the list comprehension is equivalent to the loop below.
output = []
for item, n in count.items():
if n > 2:
output.extend(repeat(item, n))
Try this:
a_list = ['book','book','cards','book','foo','foo','computer']
b_list = []
for a in a_list:
if a_list.count(a) > 2:
b_list.append(a)
print(b_list)
# ['book', 'book', 'book']
Edit: You mentioned list comprehension. You are on the right track! You can do it with list comprehension like this:
a_list = ['book','book','cards','book','foo','foo','computer']
c_list = [a for a in a_list if a_list.count(a) > 2]
Good luck!
a = ['book','book','cards','book','foo','foo','computer']
list(filter(lambda s: a.count(s) > 2, a))
Your first attempt builds a dictionary with all of the counts. You need to take this a step further to get the items that you want:
res = [k for k in test if test[k] > 2]
Now that you have built this by hand, you should check out the builtin Counter class that does all of the work for you.
If you just want to print there are better answers already, if you want to remove you can try this.
a = ['book','book','cards','book','foo','foo','computer']
countdict = {}
for word in a:
if word not in countdict:
countdict[word] = 1
else:
countdict[word] += 1
for x, y in countdict.items():
if (2 >= y):
for i in range(y):
a.remove(x)
You can try this.
def my_filter(my_list, my_freq):
'''Filter a list of strings by frequency'''
# use set() to unique my_list, then turn set back to list
unique_list = list(set(my_list))
# count frequency in unique_list
frequencies = []
for value in unique_list:
frequencies.append(my_list.count(value))
# filter frequency
return_list = []
for i, frequency in enumerate(frequencies):
if frequency > my_freq:
for _ in range(frequency):
return_list.append(unique_list[i])
return return_list
a = ['book','book','cards','book','foo','foo','computer']
my_filter(a, 2)
['book', 'book', 'book']
I'm trying to create a big list that will contain lists of strings. I iterate over the input list of strings and create a temporary list.
Input:
['Mike','Angela','Bill','\n','Robert','Pam','\n',...]
My desired output:
[['Mike','Angela','Bill'],['Robert','Pam']...]
What i get:
[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...]
Code:
for i in range(0,len(temp)):
temporary = []
while(temp[i] != '\n' and i<len(temp)-1):
temporary.append(temp[i])
i+=1
bigList.append(temporary)
Use itertools.groupby
from itertools import groupby
names = ['Mike','Angela','Bill','\n','Robert','Pam']
[list(g) for k,g in groupby(names, lambda x:x=='\n') if not k]
#[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
Fixing your code, I'd recommend iterating over each element directly, appending to a nested list -
r = [[]]
for i in temp:
if i.strip():
r[-1].append(i)
else:
r.append([])
Note that if temp ends with a newline, r will have a trailing empty [] list. You can get rid of that though:
if not r[-1]:
del r[-1]
Another option would be using itertools.groupby, which the other answerer has already mentioned. Although, your method is more performant.
Your for loop was scanning over the temp array just fine, but the while loop on the inside was advancing that index. And then your while loop would reduce the index. This caused the repitition.
temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n']
# !make sure to include this '\n' at the end of temp!
bigList = []
temporary = []
for i in range(0,len(temp)):
if(temp[i] != '\n'):
temporary.append(temp[i])
print(temporary)
else:
print(temporary)
bigList.append(temporary)
temporary = []
You could try:
a_list = ['Mike','Angela','Bill','\n','Robert','Pam','\n']
result = []
start = 0
end = 0
for indx, name in enumerate(a_list):
if name == '\n':
end = indx
sublist = a_list[start:end]
if sublist:
result.append(sublist)
start = indx + 1
>>> result
[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
I have a list like this:
l = [[1,4], [3,6], [5,4]]
I want to join the inner list with ":". I want to have the result as:
l = ['1:4', '3:6', '5:4']
How can I achieve it with Python?
You can use list comprehension to achieve this:
[':'.join(map(str, x)) for x in l]
l = [[1,4], [3,6], [5,4]]
fl = []
for x in l:
fl.append(str(x[0])+':'+str(x[1]))
print(fl) # Final List, also you can do: l = fl
But, i think that you want to do dictionaries, if this is true, you have to do:
l = [[1,4], [3,6], [5,4]]
fd = {}
for x in l:
fd[x[0]] = x[1]
print(fd) # Final Dictionary
EXPLANATION:
l = [[1,4], [3,6], [5,4]] # Your list
fl = [] # New list (here will be the result)
for x in l: # For each item in the list l:
fl.append(str(x[0])+':'+str(x[1])) # Append the first part [0] of this item with ':' and the second part [1].
print(fl)
With Dictionaries:
l = [[1,4], [3,6], [5,4]] # Your list
fd = {} # New dictionary
for x in l: # For each item in the list l:
fd[x[0]] = x[1] # Make a key called with the first part of the item and a value with the second part.
print(fd) # Final Dictionary
Also you can make a dictionary easier:
l = [[1,4], [3,6], [5,4]]
l = dict(l) # Make a dictionary with every sublist of the list (it also works with tuples), the first part of the sublist is the key, and the second the value.
You can do:
final_list = []
for i in l:
a = str(i[0])+':'+str(i[1])
final_list.append(a)
print(final_list)
My code
class getCol:
matrix = []
def __init__(self, file, delim=" "):
with open(file, 'rU') as f:
getCol.matrix = [filter(None, l.split(delim)) for l in f]
def __getitem__ (self, key):
column = []
for row in getCol.matrix:
try:
column.append(row[key])
except IndexError:
# pass
column.append("")
return column
list1 = getCol('/home/milenko/EDIs/site1/newst2.txt')[0]
list2 = getCol('/home/milenko/EDIs/site2/newst2.txt')[0]
list3 = getCol('/home/milenko/EDIs/site3/newst2.txt')[0]
list4 = getCol('/home/milenko/EDIs/site4/newst2.txt')[0]
list5 = getCol('/home/milenko/EDIs/site5/newst2.txt')[0]
list6 = getCol('/home/milenko/EDIs/site6/newst2.txt')[0]
list7 = getCol('/home/milenko/EDIs/site7/newst2.txt')[0]
list8 = getCol('/home/milenko/EDIs/site8/newst2.txt')[0]
list9 = getCol('/home/milenko/EDIs/site9/newst2.txt')[0]
list10 = getCol('/home/milenko/EDIs/site10/newst2.txt')[0]
list11 = getCol('/home/milenko/EDIs/site11/newst2.txt')[0]
list12 = getCol('/home/milenko/EDIs/site12/newst2.txt')[0]
list13 = getCol('/home/milenko/EDIs/site13/newst2.txt')[0]
list14 = getCol('/home/milenko/EDIs/site14/newst2.txt')[0]
list15 = getCol('/home/milenko/EDIs/site15/newst2.txt')[0]
list_of_lists = []
list_of_lists.append(list1)
list_of_lists.append(list2)
list_of_lists.append(list3)
list_of_lists.append(list4)
list_of_lists.append(list5)
list_of_lists.append(list6)
list_of_lists.append(list7)
list_of_lists.append(list8)
list_of_lists.append(list9)
list_of_lists.append(list10)
list_of_lists.append(list11)
list_of_lists.append(list12)
list_of_lists.append(list13)
list_of_lists.append(list14)
list_of_lists.append(list15)
result = []
# Loop the inner lists from list_of_lists, this will be list1, list2, list3...
for inner_list in list_of_lists:
# Loop each element of the inner lists
for element in inner_list:
# Make sure the element is not already in the result (this can also be done with sets)
if element not in result:
# Add the inner element to result
result.append(element)
# Sort the result
result = sorted(result)
print("\n".join(map(str, result)))
But problem is here
1.92413
10.15704
1026.00000
10260.00000
10672.43359
11.81549
1104.06055
114.21478
12.00000
12415.04102
1284.33289
13.74474
132.00000
132.86391
1376.00000
13760.00000
14442.18457
1494.04028
15.00000
I just want normal ordering from smallest to largest.How should I solve this?Is there any other alternative to sort?
It's sorting as strings. To sort as numbers, use the key argument:
result = sorted(result, key=float)
This converts each string to a float for sorting purposes, but leaves the
data as is.
Since you're assigning the result to the same identifier, you can also:
result.sort(key=float)
You need to convert the values in your list from strings to a numeric type like floats.