Home > Net >  Lookiny for the odd even
Lookiny for the odd even

Time:12-31

I can't find how to look for the odd even from this list

list_plat_mobil = ['B 1234 AB', 'B 6721 TY', 'B 1233 AY', 'B 6629 DD', 'B 1111 AM', 'B 6726 D', 'D 11223 KJ', 'AE 44677 GH', 'AE 67269 AA']

It's hard enough for me. Can you help me to slove that?

CodePudding user response:

Do you want to extract the odd/even values within your list or do you want to separate elements at odd/even indexes?

If you want the values you loop over the list and parse check all elements, if indexes are the target I would loop over and check the index.

Seems like a tutorial type question, really helpful to attack these with trial/error:) PS: Happy New Year

CodePudding user response:

Didn't understand what exactly were you looking for, a little bit more details would help, but here's an example solution:

list_plat_mobil = ['B 1234 AB', 'B 6721 TY', 'B 1233 AY', 'B 6629 DD', 'B 1111 AM', 'B 6726 D', 'D 11223 KJ', 'AE 44677 GH', 'AE 67269 AA']

oddPlats = []
evenPlats = []

for plat in list_plat_mobil:
    splittedPlatValues = plat.split()
    #The line below targets the number part of the plat, given they are all written in the same format
    numberPart = int(splittedPlatValues[1])
    
    if numberPart % 2 == 0:
        #If you need only the number part, change 'plat' to 'numberPart' in the lines below, and if you need it as a string value, then change it to 'str(numberPart)'
        evenPlats.append(plat)
    else:
        oddPlats.append(plat)

CodePudding user response:

If you want to separate your original list into odds and evens based on middle integer, this will do it for you.

list_plat_mobil = ['B 1234 AB', 'B 6721 TY', 'B 1233 AY', 'B 6629 DD', 'B 1111 AM', 'B 6726 D', 'D 11223 KJ', 'AE 44677 GH', 'AE 67269 AA']
odds = []
evens = []
for item in list_plat_mobil:
    number = int(item.split()[1])
    if (number % 2) == 0:
        evens.append(item)
    else:
        odds.append(item)

CodePudding user response:

Using list compreenssion

l = ['B 1234 AB', 'B 6721 TY', 'B 1233 AY', 'B 6629 DD', 'B 1111 AM', 'B 6726 D', 'D 11223 KJ', 'AE 44677 GH', 'AE 67269 AA']

result = [{i:'even' if int(a[1]) % 2 == 0 else 'odd'} for i,a in [(x,x.split(' ')) for x in l]]
print(result)
# [
#    {"B 1234 AB": "even"},
#    {"B 6721 TY": "odd"},
#    {"B 1233 AY": "odd"},
#    {"B 6629 DD": "odd"},
#    {"B 1111 AM": "odd"},
#    {"B 6726 D": "even"},
#    {"D 11223 KJ": "odd"},
#    {"AE 44677 GH": "odd"},
#    {"AE 67269 AA": "odd"}
# ]
  • Related