将Python列表根据元素条件分成多个列表。

huangapple go评论69阅读模式
英文:

Divide Python list into multiple lists based on element condition

问题

list1 = ['Georgia', 12344, 52353]
list2 = ['Alabama', 352947, 394567, 123437]
list3 = ['Florida', 992344, 788345]

英文:

How can I take a python list and divide it into multiple lists based on element conditions?

myList = ['Georgia', 12344, 52353, 'Alabama', 352947, 394567, 123437, 'Florida', 992344, 788345]




for each in myList:
  do stuff

result:

list1 = ['Georgia', 12344, 52353,]
list2 = ['Alabama', 352947, 394567, 123437]
list3 = ['Florida', 992344, 788345] 

答案1

得分: 2

使用 isinstance 来检查它是字符串还是整数。根据条件开始一个新的子列表或将其附加到子列表中。

newlists = []

for item in myList:
    if isinstance(item, str):
        new_sublist = [item]
        newlists.append(new_sublist)
    else:
        new_sublist.append(item)
英文:

Use isinstance to check if it's a string or int. Start a new sublist or append to the sublist depending on condition.

newlists = []

for item in myList:
    if isinstance(item, str):
        new_sublist = [item]
        newlists.append(new_sublist)
    else:
        new_sublist.append(item)

huangapple
  • 本文由 发表于 2023年3月31日 03:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定