Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

arrays - Joining elements in Python list

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

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Edit: the hard way

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...