Extract list from a list - nested

students = [["BSIT",["JOSHUA", "CRISA", "JAYMARK"]], ["BSCS",["BOBS", "CARLO", "GERALD"]]]
how can I extract items from the list and print them individually using nested for loop; the result must be
BSIT
-JOSHUA
-CRISA
-JAYMARK
BSCS
-BOBS
-CARLO
-GERALD

In python:
for cat, person_list in students:
print(cat)
for person in person_list:
print(‘-‘, person)

Related

Move Dictionary Keys to lis for particular values

I trying to make this code work:
civil_freq= { '430.00': ['aaa'],
'430.02': ['aaa'],
'430.04': ['aaa'],
'430.06': ['bbb'],
'430.08': ['bbb'],
'430.10': ['bbb'],
'430.12': ['none'],
'430.14': ['none']}
person_freq=[]
person = 'bbb'
for key in civil_freq:
if civil_freq[key] == person:
person_freq.append(civil_freq.get(key))
print(person_freq)
it return empty list, but I need smth like
['430.06', '430.08', '430.10']
Issue: You're storing the persons names in a list (within your civil_freq dictionary) but comparing it with a string (variable person). This comparison won't work.
Try this:
person = ["bbb"]
for k, v in civil_freq.items():
if v == person:
person_freq.append(k)
print(person_freq)
or change the values within your dictionary from lists to strings!

Looping over python dictionary of dictionaries

I have a python dictionary like below
car_dict=
{
'benz': {'usa':876456, 'uk':965471},
'audi' : {'usa':523487, 'uk':456879},
'bmw': {'usa':754235, 'uk':543298}
}
I need the output like below
benz,876456,965471
audi,523487,456879
bmw,754235,543298
and also in sorted form as well like below
audi,523487,456879
benz,876456,965471
bmw,754235,543298
Please help me in getting both outputs
You could do this:
car_dict= {
'benz': {'usa':876456, 'uk':965471},
'audi' : {'usa':523487, 'uk':456879},
'bmw': {'usa':754235, 'uk':543298}
}
cars = []
for car in car_dict:
cars.append('{},{},{}'.format(
car,
car_dict[car]['usa'],
car_dict[car]['uk']
))
cars = sorted(cars)
for car in cars:
print(cars)
Result
audi,523487,456879
benz,876456,965471
bmw,754235,543298
Explanation
Loop through each car and store the model, USA number and UK number in a list. Sort the list alphabetically. List it.
To print the data
# Use List comprehension to sorted list of values from car, USA, UK fields
data = [[car] + list(regions.values()) for car, regions in sorted(car_dict.items(), key=lambda x:x[0])]
for row in data:
print(*row, sep = ',')
Output
audi,523487,456879
benz,876456,965471
bmw,754235,543298
Explanation
Sort items by car
for car, regions in sorted(car_dict.items(), key=lambda x:x[0])
Each inner list in list comprehension to be row of car, USA, UK values
[car] + list(regions.values())
Print each row comma delimited
for row in data:
print(*row, sep = ',')
Are you looking to print the outputs or just organize the data in a better format for analysis.
If latter, I would use pandas and do the following
import pandas as pd
pd.DataFrame(car_dict).transpose().sort_index()
To view the output on terminal they way you requested,
for index, row in pd.DataFrame(car_dict).transpose().sort_index().iterrows():
print('{},{},{}'.format(index, row['usa'], row['uk']))
will print this out:
audi,523487,456879
benz,876456,965471
bmw,754235,543298
Find below the solution,
car_dict = {
'benz': {'usa':876456, 'uk':965471},
'audi' : {'usa':523487, 'uk':456879},
'bmw': {'usa':754235, 'uk':543298}
}
keys = list(car_dict.keys())
keys.sort()
for i in keys:
print ( i, car_dict[i] ['usa'], car_dict[i] ['uk'])
I like the list comprehension answer given by #DarrylG however you do not really need the lambda expression in this case.
sorted() will just do the sort by key by default, so you can just use :
data = [[car] + list(regions.values()) for car, regions in sorted(car_dict.items())]
I would also make another slight change. If you wanted more explicit control over the region ordering (or wanted a different ordering, you could replace the [car] + list(regions.values()) with [car, regions['usa'], regions['uk']] like this:
data = [[car, regions['usa'], regions['uk']] for car, regions in sorted(car_dict.items())]
Of course, that means that if you added more regions you would have to change this, but I prefer setting the order explicitly.

How can I group a list of strings by another list of strings using Python?

I have two lists:
List 1
filenames = ['K853.Z', 'K853.N', 'K853.E', 'K400.Z', 'K400.N', 'K400.E']
List 2
l = ['K853', 'K400']
I want to iterate through the filenames list and group the strings by the l list.
I've tried the below:
for name in filenames:
for i in l:
if i in name:
print(name)
But this just prints the first list. I've seen the Pandas groupby method but I can't figure out how to utilize it in this case.
you could just use a list generator like this:
new = [[name for name in filenames if(name.startswith(prefix))] for prefix in l]
This would provide you with a list of list, where for each index of l you would get a list of files with its prefix at the same index in the new list.

finding elements from list with different format of strings

I have a large list with elements as:
#1
#10
(on
)
0.0574
122-124
122A
Cat
Dog
elephant
elephant12
elephant-1
I want to search and be able to find only the following:
Cat
Dog
elephant
elephant12
elephant-1
i.e. elements which have an English alphabet at the beginning.
Use list comprehension:
import string
result = [item for item in my_list if item[0] in string.ascii_letters]
As #Jon commented, check if a character is a letter can simply be:
result = [item for item in my_list if item[0].isalpha()]
The above works when all items are string, and you expect items with leading English character. Change the if part as needed or even write a function if it is too complex.
If you are looking for memory-optimized version, consider generator.
You could work with a list of animals.
for example:
list=["cat","dog","elephant","fish","bird", "snake"]
then search for any of those strings in your input
I know there are better methods but I would do it with
def search(input):
for item in list:
if item in input:
result.append(item)
return result
Then you would add case ignorance precisions.
If you want the number associated with your animal name, you'll need to append the input. In this case, iterate your input.
Of course your list could take the dimension of a database if you need, for example to search for all possible existing word.

Indexing the list in python

record=['MAT', '90', '62', 'ENG', '92','88']
course='MAT'
suppose i want to get the marks for MAT or ENG what do i do? I just know how to find the index of the course which is new[4:10].index(course). Idk how to get the marks.
Try this:
i = record.index('MAT')
grades = record[i+1:i+3]
In this case i is the index/position of the 'MAT' or whichever course, and grades are the items in a slice comprising the two slots after the course name.
You could also put it in a function:
def get_grades(course):
i = record.index(course)
return record[i+1:i+3]
Then you can just pass in the course name and get back the grades.
>>> get_grades('ENG')
['92', '88']
>>> get_grades('MAT')
['90', '62']
>>>
Edit
If you want to get a string of the two grades together instead of a list with the individual values you can modify the function as follows:
def get_grades(course):
i = record.index(course)
return ' '.join("'{}'".format(g) for g in record[i+1:i+3])
You can use index function ( see this https://stackoverflow.com/a/176921/) and later get next indexes, but I think you should use a dictionary.

Resources