【问题标题】:Lookiny for the odd even寻找奇偶
【发布时间】:2021-12-31 12:21:58
【问题描述】:
我找不到如何从此列表中查找奇偶数
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']
这对我来说已经够难了。你能帮我解决这个问题吗?
【问题讨论】:
标签:
python
list
arraylist
【解决方案1】:
您是要提取列表中的奇数/偶数值还是要分隔奇数/偶数索引处的元素?
如果您想要遍历列表并解析+检查所有元素的值,如果索引是目标,我将遍历并检查索引。
似乎是一个教程类型的问题,真的有助于通过试错来解决这些问题:) PS:新年快乐
【解决方案2】:
不明白您到底在寻找什么,更多细节会有所帮助,但这里有一个示例解决方案:
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)
【解决方案3】:
如果您想根据中间整数将原始列表分成奇数和偶数,这将为您完成。
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)
【解决方案4】:
使用列表压缩
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"}
# ]