Python转字符串为数组并按相同相邻原则划为二维数组形式遇到的问题

首先,字符串为HTML中的一个元素,使用inner取出。之后使用正则表达式取出为新lsit。

str = "............"
str_option = re.findall(r"input|BorderColor", str)

取出结果为:
[‘BorderColor’, ‘BorderColor’, ‘input’, ‘input’, ‘input’, ‘input’, ‘input’, ‘input’, ‘BorderColor’, ‘BorderColor’, ‘input’, ‘input’, ‘input’, ‘input’, ‘input’]
我们需要按相邻重复的分组,这里的分组方法比较多。我使用的是:

group = [str_option[:1]]
[group[-1].append(y) if x == y else group.append([y]) for x, y in zip(str_option[:-1], str_option[1:])]

出来的结果为:
[[‘BorderColor’, ‘BorderColor’], [‘input’, ‘input’, ‘input’, ‘input’, ‘input’, ‘input’], [‘BorderColor’, ‘BorderColor’], [‘input’, ‘input’, ‘input’, ‘input’, ‘input’]]
然后重点来了,使用的时候出现了问题。代码:

temp_group_one = list()
for gg in group:
	if "input" in gg:
		temp_group_one.append(len(gg))

以上代码直接在pycharm中是正常运行的,得到的结果是正常的,temp_group_one的长度是2。
这个就很符合我们的正常思路。
但是打包之后,list出现越界。原因经过排查是因为temp_group_one本身就是空的。input并没有在gg中,但是问题是按照我们的二维数组的思路的话,这个gg已经是一维的数组了。这样子就可以了。pycharm中野确实如此,但是在exe中,gg的内容不是list,而是list的地址。我们还需要把地址转换为list。使用==list(gg)==取代gg部分即可。

补充:取出相邻重复元素:

str_new = [k for k, g in itertools.groupby(str_option)]#使用itertools库,去除列表中相邻重复元素。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值