Python列表中的连接元素 [英] Joining elements in Python list

查看:100
本文介绍了Python列表中的连接元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串(例如s='135')和一个列表(例如A=['1','2','3','4','5','6','7']),我该如何将列表中也属于's'(s的数字)的值与其他元素分开,并将其他元素串联在一起元素.此示例中的输出应为:A=['1','2','3','4','5','67']. 另一个例子: s='25' A=['1','2','3','4','5','6','7'] 输出:A=['1','2','34','5','67']

Given a string, say s='135' and a list, say A=['1','2','3','4','5','6','7'], how can I separate the values in the list that are also in 's' (a digit of s) from the other elements and concatenate these other elements. The output in this example should be: A=['1','2','3','4','5','67']. Another example: s='25' A=['1','2','3','4','5','6','7'] output: A=['1','2','34','5','67']

是否有一种无需任何导入语句即可完成此操作的方法(这样我可以更好地了解Python以及事情的运行方式)?

Is there a way of doing this without any import statements (this is so that I can get a better understanding of Python and how things work)?

我对编程还很陌生,因此不胜感激!

I am quite new to programming so any help would be appreciated!

(请注意:这是我要解决的一个较大问题的一部分).

(Please note: This is part of a larger problem that I am trying to solve).

推荐答案

您可以将itertools.groupby与用于测试您电话号码的成员资格的键(转换为字符串)一起使用.这将根据元素是否在s中进行分组.然后,列表理解将以字符串的形式加入这些组.

You can use itertools.groupby with a key that tests for membership in your number (converted to a string). This will group the elements based on whether they are in s. The list comprehension will then join the groups as a string.

from itertools import groupby

A=['1','2','3','4','5','6','7']
s=25
# make it a string so it's easier to test for membership
s = str(s)

["".join(v) for k,v in groupby(A, key=lambda c: c in s)]
# ['1', '2', '34', '5', '67']

困难的方式

您可以遍历列表并跟踪最后看到的值.这将使您测试是否需要在列表中附加新的字符串,或在最后一个字符串中附加字符. (仍然使用itertools更干净):

You can loop over the list and keep track of the last value seen. This will let you test if you need to append a new string to the list, or append the character to the last string. (Still itertools is much cleaner):

A=['1','2','3','4','5','6','7']
s=25
# make it a string
s = str(s)

output = []
last = None

for c in A:
    if last is None:
        output.append(c)
    elif (last in s) == (c in s):
        output[-1] = output[-1] + c
    else:
        output.append(c)
    last = c

output # ['1', '2', '34', '5', '67']

这篇关于Python列表中的连接元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆