简体   繁体   中英

Extracting the last element in a list with specific alphanumeric pattern

I have a list of multiple images of cities Ahmedabad, Bombay, Cuttak, Delhi that looks something like this:

["Ahmedabad_frame_1_vid_0.jpg",
 "Ahmedabad_frame_2_vid_1.jpg",
 "Ahmedabad_frame_3_vid_2.jpg",
 "Ahmedabad_frame_4_vid_3.jpg",
 "Bombay_frame_1_vid_0.jpg",
 "Bombay_frame_2_vid_1.jpg",
 "Bombay_frame_3_vid_2.jpg",
 "Bombay_frame_15_vid_3.jpg",
 "Cuttak_frame_1_vid_0.jpg",
 "Cuttak_frame_2_vid_1.jpg",
 "Cuttak_frame_3_vid_0.jpg",
 "Cuttak_frame_56_vid_3.jpg",
 "Delhi_frame_1_vid_0.jpg",
 "Delhi_frame_2_vid_1.jpg",
 "Delhi_frame_3_vid_2.jpg",
 "Delhi_frame_44_vid_3.jpg"]

Can someone please help me to execute a code in Python 3 in order to create a new list containing images of with the highest immediate adjacent frame number. The result looks something like:

["Ahmedabad_frame_4_vid_3.jpg",
 "Bombay_frame_15_vid_3.jpg",
 "Cuttak_frame_56_vid_3.jpg",
 "Delhi_frame_44_vid_3.jpg"]

The resultant list has the new elements with the highest value of "frame_#" for each specific cities. Thanks in advance!

Here is a solution you can use,

l1=["Ahmedabad_frame_1_vid_0.jpg",
 "Ahmedabad_frame_2_vid_1.jpg",
 "Ahmedabad_frame_3_vid_2.jpg",
 "Ahmedabad_frame_4_vid_3.jpg",
 "Bombay_frame_1_vid_0.jpg",
 "Bombay_frame_2_vid_1.jpg",
 "Bombay_frame_3_vid_2.jpg",
 "Bombay_frame_15_vid_3.jpg",
 "Cuttak_frame_1_vid_0.jpg",
 "Cuttak_frame_2_vid_1.jpg",
 "Cuttak_frame_3_vid_0.jpg",
 "Cuttak_frame_56_vid_3.jpg",
 "Delhi_frame_1_vid_0.jpg",
 "Delhi_frame_2_vid_1.jpg",
 "Delhi_frame_3_vid_2.jpg",
 "Delhi_frame_44_vid_3.jpg"]
l2=[]
frame=0
for i in l1:
    k=i.split("_")
    l2.append(int(k[2]))

l2.sort()
l3=l2[-4:]

l2=[]
for i in l1:
    k=i.split("_")
    for j in l3:
        if int(k[2])==j:
            l2.append(i)
            l1.remove(i)
print(l2)

output:

['Ahmedabad_frame_4_vid_3.jpg', 'Bombay_frame_15_vid_3.jpg', 'Cuttak_frame_56_vid_3.jpg', 'Delhi_frame_44_vid_3.jpg']
  1. here I have accessed only top 4 string only, you can adjust it as per your need

  2. I have deleted those strings from the original list l1 , you should modify the code as per your requirement of original list

Here is a solution using some comprehensions, given your list name is file_list :

parsed_list = [name.split("_") for name in file_list]
sorted_list = sorted(parsed_list, key=lambda element: int(element[2]))

result_dict = {s[0]: s[1:] for s in sorted_list}
result_list = [ k + "_" + "_".join(v) for k, v in result_dict.items()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM