Is it possible to run a command on every individual list item in the order they are placed? - python-3.x

I have a list in python with a random number of items. Is it possible to run the same command on every individual list item in order from 1st to last so that I can convert the output of the command into another list with different variables?
If this is possible than can I create a os.system() command for Mac OS X that runs the OS X afplay command for each individual item again in order from the new list?

Your first question sounds like something you can solve with list comprehensions https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
initial_list = [0, 9, 99, 999]
def increment(value):
"""Increment value by one."""
value += 1
return value
# This is a list comprehension, it is basically a for-loop
new_list = [increment(list_item) for list_item in initial_list]
print(f'Old list: {initial_list}')
print(f'New list: {new_list}')
Which produces:
Old list: [0, 9, 99, 999]
New list: [1, 10, 100, 1000]
For your second question, I don't have any experience with Mac OS X, but maybe you could try something like this? I hope this helps you figure it out!
import os
audio_files = ['/Media/Sound1.wav', '/Media/Sound2.wav', '/Media/Sound3.wav']
play = [os.system(f'afplay {audio_file}') for audio_file in audio_files]
play[0] # play the first audio file
# play all the files sequentially
for audio_file in play:
play[audio_file]
EDIT: Now that I read your question again, I think what you want is something like this?
import os
audio_files = ['/Media/Sound1.wav', '/Media/Sound2.wav', '/Media/Sound3.wav']
processed_audio_files = [do_something(audio_file) for audio_file in audio_files]
for audio_file in processed_audio_files:
os.system(f'afplay {audio_file}')

Related

Python doesn`t work right. Parent list is changing by changing hereditary list

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
for i in range(1, 27):
for j in range(1,27):
if j!=i:
lst = a
print(lst)
print(a)
lst.remove(i)
lst.remove(j)
print(lst)
print(a)
List 'a' is getting smaller coz i change list 'lst', wtf is this?
I just started to perform codewars kata.
By default, python creates a reference for an object. If you want to make an actual copy with new memory what you can do is:
from copy import deepcopy
lis_copy = deepcopy(lis)

PyCharm says there is no errors here, but when i run the code i get ValueError: too many values to unpack (expected 2)

enter code here
pizzas = ("4 seasons", "Neapolitan", "Pepperoni")
def display_pizzas(types):
types = list(types)
print(f"---PIZZAS({len(types)})---")
for p, x in types, range(0,len(types)):
print(f"{x}. Pizza {p}")
display_pizzas(pizzas)
im trying this weird syntax, PyCharm sees no errors here, but i get
Traceback (most recent call last):
File "...\main.py", line 9, in
display_pizzas(pizzas)
File "...\main.py", line 6, in display_pizzas
for p, x in rodzaje, range(0,len(rodzaje)):
ValueError: too many values to unpack (expected 2)
Nvm, i already found the solution whitch is:
enter code here
pizzas = ("4 seasons", "Neapolitan", "Pepperoni")
def display_pizzas(types):
types = list(types)
print(f"---PIZZAS({len(types)})---")
for p, x in zip(types, range(0,len(types))):
print(f"{x}. Pizza {p}")
bye
Maybe your new code works but it's not compiled in a pythonic way.
so I made a little refactor into your code.
you don't need to convert tuple types to the list because the tuple is already iterable you can use for loop without converting to list
instead of zip function you can user builtin enumerate
this is the whole code
from typing import Iterable
pizzas = ("4 seasons", "Neapolitan", "Pepperoni")
# refactoring Code
def display_pizzas(types: Iterable[str] = None):
print(f"---PIZZAS({len(types)})---")
for counter, pizza in enumerate(types):
print(f"{counter}. Pizza {pizza}")
display_pizzas(pizzas)

can't remove some duplicate elements from a list in python

well I was trying to remove duplicate items from a list so it has unique items and I also wanted to use for and if my code went so well but in one condition I faced something I don't understand. this is the example :
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
[1, 21, 21, 16, 20, 7]
I don't understand why !! It removes 2,3,28 which was predicted but not 21 !
any help would be great , thanks.
The best solution for this case is using set(). If you do list(set(a)) it will remove all duplicates.
Notice that set() is not the same as list() so be sure to turn it back to a list if you want to keep using list methods.
About your code, the problem with your code is that you're running on the list as you're changing it.
While you run over the items the indexes changes and that's why you miss some of the items.
You can see more clearly what happens if you add a print to understand what's x's value:
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
print(x)
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
I believe your issue is that you are changing the list while you're looping over it
Try using a.copy() to create a new copy of the list to loop over like so.
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a.copy():
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
This code will output
[1, 16, 20, 7]

Compare two lists and create multiple lists based on matching data

I have a list of 20 movies, saved like this:
library = [
['name1','director1','genre1',running_time_in_mins_1],
['name2','director2','genre2',running_time_in_mins_2],
etc up to 20
Based on that library, I need to be able to show the average running time for all movies of a particular genre. I would be looking to output something like: "Average running time for xyz is ### minutes". There could be any number of genres (6 currently in my library) or movies in the library.
I can create a list of unique genres using
genre=[]
for y in range (0,len(library)):
if (library[y][2]) not in genre:
genre.append(library[y][2])
I then thought I would create separate lists for each genre and add the matching run time but this doesn't work
for x in range (len(library)):
for z in range(0,(len(genre))):
if library[x][2] == genre[z]:
z=[]
z.append(library[x][3])
print(z)
pandas is a good library that does what you want, though it’s a little tricky to learn.
For now, try:
for genre in set(row[2] for row in library):
times = [row[3] for row in library if row[2]==genre]
print("average runtime for", genre, "is", sum(times)/len(times))
List comprehensions are a very useful tool
Getting a list of unique directors:
>>> library = [['n1', 'd1', 30], ['n2', 'd2', 40], ['n1', 'd2', 20]]
>>> set([x[1] for x in library])
set(['d2', 'd1'])
Getting a list of times for a specific name
>>> times = [x[2] for x in library if x[0] == 'n1']
[30, 20]
Calculating an average time
>>> sum(times) / len(times) # python 3
25
But list of list is really not optimal and makes the code unreadable (what's x[0]?). Depending on how you get the data, what else you want to do with it and how much time you want to spend learning more python/libraries, I would suggest: list of dictionaries, list of class, pandas dataframe or a database.

Returning a list of N dictionary keys that have the maximum integer values

my_dict = {'label': 6, 'label_2': 5, 'label_3': 9, 'label_4': 12}
I would like to create a list that will contain the top 2 (or 3, or 4, or 50... this will vary) dictionary keys, according to their highest values. So in the example above if I wanted the top 2, I should get:
['label_3', 'label_4']
for top 3 I should get:
['label', 'label_3', 'label_4']
And so on.
After reading some other stackoverflow threads, I've been experimenting with heapq, but can't get it to work the way I want. Would appreciate some help.
Of course, the moment I post here, I find a solution (thanks to the heapq documentation). This works:
my_list = heapq.nlargest(3, my_dict, key=my_dict.get)
This will go over my_dict and return the keys with the 3 largest values.
Thanks.

Resources