英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论