在列表中拆分字符串

时间:2018-02-19 02:46:11

标签: python string split

我在python中有一个列表:

if num in my_list:
     #do something

我知道如果我想分割一个字符串列表,我可以使用split:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> if 3 in x:
...     print("3 found")
... 
3 found

但它已经是我需要它的形式,我想评估字符串值而不是附加到它的int。基本上是这样的:

hand_of_cards = ["4H", "6D", "7D", "7C", "3C"]

for char in hand_of_cards:
    if hand_of_cards[1] == "S" and hand_of_cards[1] == "C":
        black_counter += 1

3 个答案:

答案 0 :(得分:2)

这是一种方式:

x = "4H"

[x[:-1], x[-1]]  # ['4', 'H']

通过列表理解将其应用到列表中:

[[x[:-1], x[-1]] for x in lst]

# [['4', 'H'], ['6', 'D'], ['7', 'D'], ['7', 'C'], ['3', 'C']]

答案 1 :(得分:1)

您可以将map与正则表达式一起使用:

import re
hand_of_cards = ["4H", "6D", "7D", "7C", "3C", "JH"]
new_cards = list(map(lambda x:re.findall('\d+|[A-Z]+', x), hand_of_cards))

输出:

[['4', 'H'], ['6', 'D'], ['7', 'D'], ['7', 'C'], ['3', 'C'], ['JH']]

答案 2 :(得分:0)

试试这段代码!

hand_of_cards = ["4H", "6D", "7D", "7C", "3C"]

for i in range(0,len(hand_of_cards)):
    l=list(hand_of_cards[i])
    hand_of_cards.remove(hand_of_cards[i])
    hand_of_cards.insert(i,l)

print(hand_of_cards)

输出

[['4','H'],['6','D'],['7','D'],['7','C'],['3',' C']