2013-02-08 54 views
5
myList = [ 4,'a', 'b', 'c', 1 'd', 3] 

如何將此列表拆分成一個包含字符串和其他包含優雅/ Python的方式整數兩個列表?Python的 - 分裂列表包含字符串和整數

輸出:

myStrList = [ 'a', 'b', 'c', 'd' ] 

myIntList = [ 4, 1, 3 ] 

注:沒有執行這樣的列表,就是想如何找到一個優雅的答案(有沒有?)這樣的問題。

+1

我想你需要一個正則表達式 – bozdoz 2013-02-08 16:25:57

+0

恕我直言,這是非常醜陋solution.i'd而遍歷列表和分裂。 – ayyayyekokojambo 2013-02-08 16:27:08

+3

檢查類型是非空格的,就像創建這樣的混合類型列表一樣。也許你應該看到關於根據輸入的*目的分割數據,而不是稍後再對它進行攻擊? – millimoose 2013-02-08 16:28:03

回答

12

正如其他人在評論中提到的那樣,你應該真的開始考慮如何擺脫列表中包含非同類數據的列表。但是,如果真的無法做,我會使用一個defaultdict:

from collections import defaultdict 
d = defaultdict(list) 
for x in myList: 
    d[type(x)].append(x) 

print d[int] 
print d[str] 
8

您可以使用列表理解: -

>>> 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'] 
+1

如果事先知道類型並且沒有太多的話,這很有效:) – mgilson 2013-02-08 16:31:39

+1

@mgilson ..嗯。是的。儘管我喜歡你的方式。 :) – 2013-02-08 16:32:11

3
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'] 
1

拆分列表按照類型在原單列表

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]} 
0

我要回答一個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 
-1
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) 
+0

儘管此代碼可能會回答問題,但提供有關爲何和/或代碼如何回答問題的其他上下文可提高其長期價值。 – 2017-03-13 12:50:52