[['s', 'a', 'b', 't'], ['s', 'c', 'd', 't'], ['s', 'c', 'e', 't','g']]
I want to count how many elements are in each list of the list.
so,[4,4,5].How can i do that in python?
Just use len for each element on the given list:
l = [['s', 'a', 'b', 't'], ['s', 'c', 'd', 't'], ['s', 'c', 'e', 't','g']]
[len(x) for x in l] # [4, 4, 5]
you can utilize the len() function. It takes a list as a parameter and returns the elements count.
python len function
Related
I have the following 2D list:
test_list = [['A', 'B', 'C'], ['I', 'L', 'A', 'C', 'K', 'B'], ['J', 'I', 'A', 'B', 'C']]
I want to compare the 1st list elements of the 2D array test_list[0] with all other lists. If the elements ['A', 'B', 'C'] are present in all other lists then it should print any message such as "All elements are similar".
I have tried this piece of code but it is not working as I expected:
test_list = [['A', 'B', 'C'], ['I', 'L', 'A', 'C', 'K', 'B'], ['J', 'I', 'A', 'B', 'C']]
for idx,ele in enumerate(p):
result = set(test_list [0]).intersection(test_list [(idx + 1) % len(temp_d)])
print(result)
Expected Output:
The elements of the list ['A', 'B', 'C'] are present in all other lists.
You can use the all(...) function - or remove all elements from the bigger list from your smaller one converted to set. If the set.difference() is Falsy (i.e. all elements were removed) they were all contained in it:
test_list = [['A', 'B', 'C'], ['I', 'L', 'A', 'C', 'K', 'B'], ['J', 'I', 'A', 'B', 'C']]
s = test_list[0]
for e in test_list[1:]:
if all(v in e for v in s):
print(e, "contains all elements of ", s)
s = set(s)
for e in test_list[1:]:
# if all elements of s are in e the difference will be an empty set == Falsy
if not s.difference(e):
print(e, "contains all elements of ", s)
Output:
['I', 'L', 'A', 'C', 'K', 'B'] contains all elements of ['A', 'B', 'C']
['J', 'I', 'A', 'B', 'C'] contains all elements of ['A', 'B', 'C']
['I', 'L', 'A', 'C', 'K', 'B'] contains all elements of {'A', 'B', 'C'}
['J', 'I', 'A', 'B', 'C'] contains all elements of {'A', 'B', 'C'}
For each letter in the first list see if they are in the second and third list and return the boolean.
Then see if the set of the new list equals True
test_list = [['A', 'B', 'C'], ['I', 'L', 'A', 'C', 'K', 'B'], ['J', 'I', 'A', 'B', 'C']]
bool = ([x in test_list[1]+test_list[2] for x in test_list[0]])
if list(set(bool))[0] == True:
print('All elements are similar')
>>> All elements are similar
Given a list of lists:
list_format = [['a', 'c', 'f', 'b'], ['j', 'l', 'o', 'c'], ['q', 's', 'v', 'e']]
'c', 'f', 'b' must be mapped to 'a'
'l', 'o', 'c' must be mapped to 'j'
's', 'v', 'e' must be mapped to 'q'
The output should look like this:
[['a','c'],['a','f'],['a','b'],['j','l'],['j','o'],['j','c'],['q','s'],['q','v'],['q','e']]
I've tried so far:
list_dict = {element[0]:element[1:] for element in list_format}
newer_lst = []
for key, value in list_dict.items():
newer_lst.append((key, value))
newer_lst
Gives me the output of tuples:
[('a', ['c', 'f', 'b']), ('j', ['l', 'o', 'c']), ('q', ['s', 'v', 'e'])]
I'm newer at this and trying to rearrange, any advice would be awesome, been stuck for days with trial and error(searched google countless times and constantly googling. I feel I'm getting close but can't seem to put it together.
Here is a one-liner, using slicing:
[[i[0],j] for i in list_format for j in i[1:]]
gives:
[['a', 'c'], ['a', 'f'], ['a', 'b'], ['j', 'l'], ['j', 'o'], ['j', 'c'], ['q', 's'], ['q', 'v'], ['q', 'e']]
Also, if you iterate through your value variable, you get your result:
list_dict = {element[0]:element[1:] for element in list_format}
newer_lst = []
for key, value in list_dict.items():
for i in value:
newer_lst.append((key, i))
print(newer_lst)
You don't need to create a loop, just loop on sub array and append new sub array to main output array on the fly, like new_list.append([lst[0], item])
new_list = []
for lst in list_format:
for item in lst[1:]:
new_list.append([lst[0], item])
print(new_list)
#output
#[['a', 'c'], ['a', 'f'], ['a', 'b'], ['j', 'l'], ['j', 'o'], ['j', 'c'], ['q', 's'], ['q', 'v'], ['q', 'e']]
I have an arbitrary length list of strings I want to sort in alphabetical order unless it is a specific string, then I want those to have "priority" over others and come first.
Example input:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
I want to sort the list such that the values ['c', 'g', 'e'] come first in that order then the rest of the list is sorted alphabetically.
Result:
['c', 'g', 'e', 'a', 'b', 'd', 'f']
I'm trying to figure out how to create a key function I can pass to sorted.
This should work:
def key_func(elem):
if elem == "c":
return chr(0)
if elem == "g":
return chr(1)
if elem == "e":
return chr(2)
return elem
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
lst.sort(key=key_func)
print(lst)
Output:
['c', 'g', 'e', 'a', 'b', 'd', 'f']
Just ensure your list doesn't contain chr(0), chr(1) or chr(2)
If you want different "priority" strings, change key_func to this:
priority = ['c', 'g', 'e']
def key_func(elem):
if elem not in priority:
return elem
return chr(priority.index(elem))
I have a dictionary of 'event' names (key) and multiplicities (value) for distributions. I want to convert this dictionary into a list to reduce run time to use binary search. I do not want to add another for loop as I feel like that will increase my run time.
I have tried looping through my dictionary and appending while multiplying the key by value but that only gives me the key*value instead of a number of keys that is the value number.
mydict = {'a':5, 'b':7, 'c':10, 'd':2}
myrichard = []
for x,y in mydict.items():
myrichard.append(x * y)
I would want to have the output of ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd'] but I get the output of ['aaaaa', 'bbbbbbb', 'cccccccccc', 'dd'].
You want the list.extend method.
>>> mydict = {'a':5, 'b':7, 'c':10, 'd':2}
>>> myrichard = []
>>> for x,y in mydict.items():
... myrichard.extend(x * y)
...
>>> myrichard
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd']
Assuming I have something like the following:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
And I have to change it to:
['a', 'b', 'f', 'c', 'd', 'e', 'g']
What is the most efficient way to do this?
UPDATE: I actually need the elements shifted, not swapped. Note the change to my example above.
I don't know if by "efficient" you mean "in a clear/readable way", or if you're referring to performance. If it's the former and you want to do the replacement in-place, you can use the handy [] operator of lists:
def arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr[2, 5] = arr[5, 2]
assert arr == ['a', 'b', 'f', 'd', 'e', 'c', 'g']
Update: The question is not about swapping two elements, it's about moving an element to another position. To do that in-place, you can use some of the Java ArrayList methods that let you add and remove elements from a given position. I think this is quite readable:
def arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
arr.add(2, arr.remove(5))
assert arr == ['a', 'b', 'f', 'c', 'd', 'e', 'g']