myList = [ 4,'a', 'b', 'c', 1 'd', 3]
如何将此列表拆分成一个包含字符串和其他包含优雅/ Python的方式整数两个列表?Python的 - 分裂列表包含字符串和整数
输出:
myStrList = [ 'a', 'b', 'c', 'd' ]
myIntList = [ 4, 1, 3 ]
注:没有执行这样的列表,就是想如何找到一个优雅的答案(有没有?)这样的问题。
myList = [ 4,'a', 'b', 'c', 1 'd', 3]
如何将此列表拆分成一个包含字符串和其他包含优雅/ Python的方式整数两个列表?Python的 - 分裂列表包含字符串和整数
输出:
myStrList = [ 'a', 'b', 'c', 'd' ]
myIntList = [ 4, 1, 3 ]
注:没有执行这样的列表,就是想如何找到一个优雅的答案(有没有?)这样的问题。
正如其他人在评论中提到的那样,你应该真的开始考虑如何摆脱列表中包含非同类数据的列表。但是,如果真的无法做,我会使用一个defaultdict:
from collections import defaultdict
d = defaultdict(list)
for x in myList:
d[type(x)].append(x)
print d[int]
print d[str]
您可以使用列表理解: -
>>> myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
>>> myIntList = [x for x in myList if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']
如果事先知道类型并且没有太多的话,这很有效:) – mgilson 2013-02-08 16:31:39
@mgilson ..嗯。是的。尽管我喜欢你的方式。 :) – 2013-02-08 16:32:11
def filter_by_type(list_to_test, type_of):
return [n for n in list_to_test if isinstance(n, type_of)]
myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
nums = filter_by_type(myList,int)
strs = filter_by_type(myList,str)
print nums, strs
>>>[4, 1, 3] ['a', 'b', 'c', 'd']
拆分列表按照类型在原单列表
myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
types = set([type(item) for item in myList])
ret = {}
for typeT in set(types):
ret[typeT] = [item for item in myList if type(item) == typeT]
>>> ret
{<type 'str'>: ['a', 'b', 'c', 'd'], <type 'int'>: [4, 1, 3]}
我要回答一个Python FAQ“怎么做来概括这个线程发现你写了一个方法,它可以以任何顺序,范围很窄的类型来引用参数?“
假设所有参数左到右的顺序并不重要,试试这个(基于@mgilson的答案):
def partition_by_type(args, *types):
d = defaultdict(list)
for x in args:
d[type(x)].append(x)
return [ d[t] for t in types ]
def cook(*args):
commands, ranges = partition_by_type(args, str, range)
for range in ranges:
for command in commands:
blah blah blah...
现在,您可以拨打cook('string', 'string', range(..), range(..), range(..))
。参数顺序在其类型内是稳定的。
# TODO make the strings collect the ranges, preserving order
import strings;
num=strings.digits;
str=strings.letters;
num_list=list()
str_list=list()
for i in myList:
if i in num:
num_list.append(int(i))
else:
str_list.append(i)
尽管此代码可能会回答问题,但提供有关为何和/或代码如何回答问题的其他上下文可提高其长期价值。 – 2017-03-13 12:50:52
我想你需要一个正则表达式 – bozdoz 2013-02-08 16:25:57
恕我直言,这是非常丑陋solution.i'd而遍历列表和分裂。 – ayyayyekokojambo 2013-02-08 16:27:08
检查类型是非空格的,就像创建这样的混合类型列表一样。也许你应该看到关于根据输入的*目的分割数据,而不是稍后再对它进行攻击? – millimoose 2013-02-08 16:28:03