-2

I'm wondering which will be the best pythonic way to get all the same prefix for the values in a list.

  • Rule #1: the word will be compound by the following parts: prefix + name + end (separated by '_'.
  • Rule #2: all the word parts will be variable in length
  • Rule #3: the end of the word is a two-character string starting with letter 'A' followed by a integer from 0-9 and could be the same for all the values in the list
  • Rule #4: The names of each value will never be repeated in a list
  • Rule #5: all the values in the list will have the same "unknown" prefix

Here are some examples from the rules listed above:

list1 = ['4_AR_P3_A0', '4_BCML_A0', '4_PA_RU_LR_A0', '4_Routes_A0']
get_prefix(list1) # output: '2'
list2 = ['MPL_TER_LA_Desse_A1', 'MPL_TER_LA_Magnit_Mach_A0', 'MPL_TER_LA_LR_A6', 'MPL_TER_LA_Routes_A0']
get_prefix(list2) # output: 'MPL_TER_LA'
Matt_Geo
  • 287
  • 1
  • 3
  • 13
  • Does this answer your question? https://stackoverflow.com/questions/11263172/what-is-the-pythonic-way-to-find-the-longest-common-prefix-of-a-list-of-lists – Pranav Hosangadi Sep 13 '22 at 14:53

2 Answers2

1

use os.path.commonprefix(). Please check out: os.path

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 23 '22 at 11:08
0

Thanks to Pranav:

import os
s_l = []
for v in list1: s_l.append(v.split('_'))
print(os.path.commonprefix(s_l))
Matt_Geo
  • 287
  • 1
  • 3
  • 13