I am having a problem with my code and getting it to work. Im not sure if im sorting this correctly. I am trying to sort with out lambda pandas or itemgetter.
Here is my code that I am having issues with.
with open('ManufacturerList.csv', 'r') as man_list:
ml = csv.reader(man_list, delimiter=',')
for row in ml:
manufacturerList.append(row)
print(row)
with open('PriceList.csv', 'r') as price_list:
pl = csv.reader(price_list, delimiter=',')
for row in pl:
priceList.append(row)
print(row)
with open('ManufacturerList.csv', 'r') as service_list:
sl = csv.reader(service_list, delimiter=',')
for row in sl:
serviceList.append(row)
print(row)
new_mfl = (sorted(manufacturerList, key='None'))
new_prl = (sorted(priceList, key='None'))
new_sdl = (sorted(serviceList, key='None'))
for x in range(0, len(new_mfl)):
new_mfl[x].append(priceList[x][1])
for x in range(0, len(new_mfl)):
new_mfl[x].append(serviceList[x][1])
new_list = new_mfl
inventoryList = (sorted(list, key=1))
i have tried to use the def function to try to get it to work but i dont know if im doing it right. This is what i tried.
def new_mfl(x):
return x[0]
x.sort(key=new_mfl)
2条答案
按热度按时间bvjxkvbb1#
You can do it like this:
The
key
argument is the function that extracts the field of the CSV that you want to sort by.cuxqih212#
sort:
sorted_mfl = sorted(manufacturerList, key=lambda x: x[0])
there are different Dialects and Formatting Parameters that allow to handle input and output of data from comma separated value files; Maybe it could be used in a way with fewer statements using the correct delimiter which depends on the type of data you handle, this would be added to using built in methods like
split
for string data or another method to sort and manipulatelists
, for example for single column data,delimiter=','
separate data by comma and it would iterate trough value by value and not as a list of lists when you callcsv.reader
This is achieved because I am using lists that contain singular values, since for columns or lists that are of the form
sorted_mfl = {'First Name' : ['name', 'name', 'name'], 'Seond Name ' : [...], 'ID':[...]}, new_prl = ['example', 'example', 'example'] new_sdl = [...]
the data would be added by something likesorted_mfl + new_prl + new_sdl
and since different modules are also used to set and manage comma separated files, you should add more information to your question like the data type you use or create a reproducible example using pandas , hope this can help.