0

I would like to know if a given strings starts with some strings from a list.

p1 = ["I2101", "I222", "I7102", "I252"]
g1 = ["I21", "I22", "I252"]
g2 = ["I71"]
for p in p1:
    if p in g1:
        print("grupo1")
    elif p in g2:
        print("grupo2")

It should show grupo1 , grupo1, grupo2, grupo1 but It only works with I252 because it's the same as g1[2]

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Nelly Louis
  • 157
  • 2
  • 8
  • I'm sure that you can find existing advice for checking whether a string has a specific prefix using Python :) For example, [this question](https://stackoverflow.com/questions/32982953/in-python-3-how-do-i-determine-if-a-prefix-is-in-a-string) – MyStackRunnethOver Jun 26 '19 at 22:48

1 Answers1

2
p1 = ["I2101", "I222", "I7102", "I252"]

g1 = ["I21", "I22", "I252"]
g2 = ["I71"]

for p in p1:
    if any(p.startswith(g) for g in g1):
        print('{}: Grupo 1'.format(p))
    elif any(p.startswith(g) for g in g2):
        print('{}: Grupo 2'.format(p))

Prints:

I2101: Grupo 1
I222: Grupo 1
I7102: Grupo 2
I252: Grupo 1

Edit (alternative version):

g = [(k, 'Grupo 1') for k in g1] + [(k, 'Grupo 2') for k in g2]
print([v[1] for p in p1 for v in g if p.startswith(v[0])])

Prints:

['Grupo 1', 'Grupo 1', 'Grupo 2', 'Grupo 1']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91