what I am trying to do here is append the element form the_list with the greatest value
in the [-1] position . i started by creating an index dictionary for the elements in the_list but i started to get lost in the logic flow.
the_list = [['a','b','c','1'],['b','c','e','4'],['d','e','f','2']]
D_indx_element = {}
D_indx_value = {}
output = []
temp = []
for i,k in zip(range(0,len(the_list)),the_list):
D_indx_element[i] = k
temp.append(int(k[-1]))
D_indx_value[i] = int(k[-1])
in the end i would like to have:
output = [['b','c','e','4']]
since 4 is greater than 1 and 2
Use max:
>>> the_list = [['a','b','c','1'],['b','c','e','4'],['d','e','f','2']]
>>> max(the_list, key=lambda x:int(x[-1]))
['b', 'c', 'e', '4']
Without lambda:
def func(x):
return int(x[-1])
max(the_list, key=func)
#['b', 'c', 'e', '4']
Related
I have this function:
datapoints = 3
abc = ['a','b','c', ... 'z']
character = abc[:datapoints]
for n in character:
values = int(askstring("Title", "Value: ")) # 1
dat1= character.pop(0) # a
dat2 = dat1 + "," + str(values) # a,1
d = dat2.split(",") # [a,1]
data = list((d, d)) # [['a', '1']]
print(data)
unfortunately, the data gets overridden after every loop and therefore I get this:
[['a', '1'],['a', '1']]
[['b', '2'],['b', '2']]
[['c', '3'],['c', '3']]
instead of this:
[['A', 1],['B', 2]],['C', 3]]
I have tried also list(zip(d, d)), but that doesn't help at all:
[('a', 'a'),('1', '1')]
[('b', 'b'),('2', '2')]
[('c', 'c'),('3', '3')]
Thank you for any help
Your loop is overriding the values of data and d every time, you want to put data = [] at the beginning of the loop and data.append(d) in the middle of the loop. Example:
data = []
for n in character:
d = ...
data.append(d)
Your loop is popping characters from character and looping over the list. You want to do either:
for n in character:
dat1 = n
Or:
while character:
dat1 = character.pop(0)
In a python list, I want to delete all elements repeated less than 'k'.
for example if k == 3 then if our list is:
l = [a,b,c,c,c,a,d,e,e,d,d]
then the output must be:
[c,c,c,d,d,d]
what is a fast way to do that (my data is large), any good pythonic suggestion?
this is what I coded but I don't think it is the fastest and most pythonic way:
from collections import Counter
l = ['a', 'b', 'c', 'c', 'c', 'a', 'd', 'e', 'e', 'd', 'd']
counted = Counter(l)
temp = []
for i in counted:
if counted[i] < 3:
temp.append(i)
new_l = []
for i in l:
if i not in temp:
new_l.append(i)
print(new_l)
You can use collections.Counter to construct a dictionary mapping values to counts. Then use a list comprehension to filter for counts larger than a specified value.
from collections import Counter
L = list('abcccadeedd')
c = Counter(L)
res = [x for x in L if c[x] >=3]
# ['c', 'c', 'c', 'd', 'd', 'd']
A brute-force option would be to get the number of occurrences per item, then filter that output. The collections.Counter object works nicely here:
l = [a,b,c,c,c,a,d,e,e,d,d]
c = Counter(l)
# Counter looks like {'a': 2, 'b': 1, 'c': 3...}
l = [item for item in l if c[item]>=3]
Under the hood, Counter acts as a dictionary, which you can build yourself like so:
c = {}
for item in l:
# This will check if item is in the dictionary
# if it is, add to current count, if it is not, start at 0
# and add 1
c[item] = c.get(item, 0) + 1
# And the rest of the syntax follows from here
l = [item for item in l if c[item]>=3]
I would use a Counter from collections:
from collections import Counter
count_dict = Counter(l)
[el for el in l if count_dict[el]>2]
Any drawback with this option?
l = ['a','b','c','c','c','a','d','e','e','d','d']
res = [ e for e in l if l.count(e) >= 3]
#=> ['c', 'c', 'c', 'd', 'd', 'd']
I want to combine two elements in a list based on a given condition.
For example if I encounter the character 'a' in a list, I would like to combine it with the next element. The list:
['a', 'b', 'c', 'a', 'd']
becomes
['ab', 'c', 'ad']
Is there any quick way to do this?
One solution I have thought of is to create a new empty list and iterate through the first list. As we encounter the element 'a' in list 1, we join list1[index of a] and list1[index of a + 1] and append the result to list 2. However I wanted to know if there is any way to do it without creating a new list and copying values into it.
This does not create a new list, just modifies the existing one.
l = ['a', 'b', 'c', 'a', 'd']
for i in range(len(l)-2, -1, -1):
if l[i] == 'a':
l[i] = l[i] + l.pop(i+1)
print(l)
If you don't want to use list comprehension to create a new list (maybe because your input list is huge) you could modify the list in-place:
i=0
while i < len(l):
if l[i]=='a':
l[i] += l.pop(i+1)
i += 1
Use a list comprehension with an iterator on your list. When the current iteratee is a simply join it with the next item from the iterator using next:
l = ['a', 'b', 'c', 'a', 'd']
it = iter(l)
l[:] = [i+next(it) if i == 'a' else i for i in it]
print l
# ['ab', 'c', 'ad']
Well, if you don't want to create a new list so much, here we go:
from itertools import islice
a = list("abcdabdbac")
i = 0
for x, y in zip(a, islice(a, 1, None)):
if x == 'a':
a[i] = x + y
i += 1
elif y != 'a':
a[i] = y
i += 1
try:
del a[i:]
except:
pass
you could use itertools.groupby and group by:
letter follows a or
letter is not a
using enumerate to generate the current index, which allows to fetch the previous element from the list (creating a new list but one-liner)
import itertools
l = ['a', 'b', 'c', 'a', 'd']
print(["".join(x[1] for x in v) for _,v in itertools.groupby(enumerate(l),key=lambda t: (t[0] > 0 and l[t[0]-1]=='a') or t[1]=='a')])
result:
['ab', 'c', 'ad']
This is easy way. Mb not pythonic way.
l1 = ['a', 'b', 'c', 'a', 'd']
do_combine = False
combine_element = None
for el in l1:
if do_combine:
indx = l1.index(el)
l1[indx] = combine_element + el
do_combine = False
l1.remove(combine_element)
if el == 'a':
combine_element = el
do_combine = True
print(l1)
# ['ab', 'c', 'ad']
I want to compare sublists of my list and return the unmatched variables
input is
lst = [['2','b'], ['!d','e'], ['s','f', 'd'], ['24','!b'], ['and','7']]
desired output
out_lst = [['2','b'],['!d','e'],['s','f','d'] ['24','!b'], ['and', '7']['e','s','f'] ['2','24']]
I am comparing my sublists with each other and if I find d in one sublist ['s', 'f', 'd'] and !d in another sublist ['!d', 'e'], I merge both and add only the unmatched variables that is ['e', 's', 'f'] as another sublist at the end of the list. How can it be done efficiently?
import itertools
def reduction(self):
for i in range(0,len(self.lst)):
for j in range(0,len(self.lst[i])):
if not any(x in [i][j]== "!"+x in [i][j]):
self.new_lst.append()
else:
itertools.chain(x , ~x)
self.new_lst.pop()
print new_lst.reduction()
I get errors because of matching a list with a string. Is there a better way of implementing this logic?
Try this
def reduction(self):
res = self.lst[:]
for i in self.lst:
for j in i:
for k in self.lst:
if "!"+j in k:
temp = i[:]
temp.remove(j)
temp2 = k[:]
temp2.remove("!"+j)
res.append(temp2+temp)
self.lst = res[:]
return self.lst
I have a nested list like this.
[['a','g','c'],['e','c','g']...]
I am trying to see if third entry is equal to second entry in the list. If it is, I want to return first entry in that list. So since 3rd entry in list 1 is c, I want to look for c in second entry in all the list. Since list 2 has corresponding value in 2nd entry, I want to return e, then append that to nested list 1. There are multiple lists,and want to do it for all the list.
So
[['a','g','c','e']...]]
You could try the below,
>>> l = [['a','g','c'],['e','c','g']]
>>> i = l[0][2] # stores the value of 2nd index of l[0] to the variable i
>>> m = l[0] # assigns the 0th index of l to m
>>> for j in l[1:]:
if i == j[1]:
m.append(j[0])
>>> m
['a', 'g', 'c', 'e']
A complex example.
>>> l = [['a','g','c'],['e','c','g'], ['m','c','g'], ['j','c','g'], ['k','f','g'], ['p','c','g']]
>>> i = l[0][2]
>>> m = l[0]
>>> for j in l[1:]:
if i == j[1]:
m.append(j[0])
>>> m
['a', 'g', 'c', 'e', 'm', 'j', 'p']
k=[['a','g','c'],['e','c','g'],['m','c','g'],['j','c','g'],['k','f','g'],['p','g','k']]
print [x+y[:1] for x,y in zip(k,k[1:]) if x[2]==y[1]]
Try this.