myList = [ 4,'a', 'b', 'c', 1 'd', 3]
如何将此列表拆分为两个列表,其中一个包含字符串,另一个包含优雅/pythonic方式的整数?
输出:
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']
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 常见问题来总结这个线程:“你如何编写一个以任意顺序、范围很窄的类型接受参数的方法?”
假设所有参数的从左到右的顺序并不重要,试试这个(基于@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
n = (input("Enter string and digits: "))
d=[]
s=[]
for x in range(0,len(n)):
if str(n[x]).isdigit():
d.append(n[x])
else
s.append(n[x])
print(d)
print(s)
编辑1:这是另一个解决方案
import re
x = input("Enter any string that contains characters and integers: ")
s = re.findall('[0-9]',x)
print(s)
c = re.findall('[a-z/A-Z]',x)
print(c)
您可以使用此代码作为示例,使用函数 isdigit() 创建两个不同的列表,该函数检查字符串中的整数。
ip=['a',1,2,3]
m=[]
n=[]
for x in range(0,len(ip):
if str(ip[x]).isdigit():
m.append(ip[x])
else:n.append(ip[x])
print(m,n)
myList = [ 4,'a', 'b', 'c', 1 'd', 3]
myList_string = []
myList_number = []
for a in myList:
if type(a) == int or type(a) == float:
myList_number.append(a)
elif type(a) == str:
myList_string.append(a)
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)