如何对一串字符串元素进行分组

时间:2018-12-20 11:54:36

标签: python

我有一个像这样的字符串:

"Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

,并且我尝试列出一个相同的列表。这是我的代码:

List = []
ls = []
for el in input:
  if el == 'Hotel_Rooms: ':
      pass
  else:
    if el !=',': 
      ls.extend(el)
    else:
      List.append(ls)
print List

但是结果太奇怪了。你能让我知道如何改善我的代码吗?

谢谢

3 个答案:

答案 0 :(得分:3)

尝试使用collections.Counter,如下所示:

from collections import Counter
text= "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"
C = Counter(text.split('Hotel_Rooms: ')[1].split(','))
print [[k,]*v for k,v in C.items()]

答案 1 :(得分:2)

您也可以执行groupby

from itertools import groupby

string = "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

# convert string to sorted list
vals = sorted([x.strip() for x in string.split(':')[1].split(',')])

print([list(g) for k,g in groupby(vals)])

[['R1', 'R1', 'R1', 'R1'], ['R11'], ['R15', 'R15'], ['R2', 'R2', 'R2', 'R2'], ['R3', 'R3', 'R3', 'R3'], ['R4', 'R4', 'R4', 'R4'], ['R5', 'R5', 'R5', 'R5'], ['R6', 'R6', 'R6', 'R6'], ['R8', 'R8']]

答案 2 :(得分:1)

您的代码当前仅遍历输入字符串,并将逗号与其他字符分隔到不同的列表中。我认为那不是您想要的。您似乎想将类似的房间分组。您可以为此使用collections.defaultdict()

from collections import defaultdict

s = "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

# Split rooms from 'Hotel_Rooms'
_, rooms = s.split(':')

# Group rooms into dictionary
room_dict = defaultdict(list)
for room in rooms.strip().split(','):
    room_dict[room].append(room)

print(list(room_dict.values()))
# [['R15', 'R15'], ['R11'], ['R5', 'R5', 'R5', 'R5'], ['R4', 'R4', 'R4', 'R4'], ['R8', 'R8'], ['R2', 'R2', 'R2', 'R2'], ['R3', 'R3', 'R3', 'R3'], ['R6', 'R6', 'R6', 'R6'], ['R1', 'R1', 'R1', 'R1']]