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

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

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?

  1. myList = ['Georgia', 12344, 52353, 'Alabama', 352947, 394567, 123437, 'Florida', 992344, 788345]
  2. for each in myList:
  3. do stuff

result:

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

答案1

得分: 2

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

  1. newlists = []
  2. for item in myList:
  3. if isinstance(item, str):
  4. new_sublist = [item]
  5. newlists.append(new_sublist)
  6. else:
  7. 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.

  1. newlists = []
  2. for item in myList:
  3. if isinstance(item, str):
  4. new_sublist = [item]
  5. newlists.append(new_sublist)
  6. else:
  7. 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:

确定