Joining elements in Python list

2024/10/6 18:35:57

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

Answer

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 groupbyA=['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 = Nonefor c in A:if last is None:output.append(c)elif (last in s) == (c in s):output[-1] = output[-1] + celse:output.append(c)last = coutput # ['1', '2', '34', '5', '67']
https://en.xdnf.cn/q/118924.html

Related Q&A

Python - Count letters in random strings

I have a bunch of integers which are allocated values using the random module, then converted to letters depending on their position of the alphabet.I then combine a random sample of these variables in…

Looping until a specific key is pressed [duplicate]

This question already has answers here:detect key press in python, where each iteration can take more than a couple of seconds?(4 answers)Closed 2 years ago.I was trying to make a while loop which wou…

Getting sub-dataframe after sorting and groupby

I have a dataframe dfas:Election Year Votes Vote % Party Region 0 2000 42289 29.40 Janata Dal (United) A 1 2000 27618 19.20 Rashtriya Ja…

Use .vss stencil file to generate shapes by python code (use .vdx?)

I want to have my python program generate visio drawings using shapes from a stencil (.vss) file. How can I do that? I think I could generate the xml formatted .vdx file, but there isnt a lot of docum…

How can I capture detected image of object Yolov3 and display in flask

I am working on Real Time Object Detection using YOLOv3 with OpenCV and Python. Its works well. Currently I try to capture detected image of object and display in flask. Do someone know how to implemen…

ValueError: Shapes (2, 1) and () are incompatible

I have to use Tensorflow 0.11 for this code repo and this is the error I get:(py35) E:\opensource_codes\gesture_recognition\hand3d-master>python run.py Traceback (most recent call last):File "r…

Subtotals for Pandas pivot table index and column

Id like to add subtotal rows for index #1 (ie. Fruits and Animal) and subtotal columns for columns (ie. 2015 and 2016).For the subtotal columns, I could do something like this, but it seems inefficient…

Create two new columns derived from original columns in Python

I have a dataframe, df, that contains two columns that contain quarter values. I would like to create two more columns that are the equivalent "long dates". Data ID Quarter Delivery A …

In dataframe: how to pull minutes and seconds combinedly(mm:ss) from timedelta using python

i have already tried these but by this we can only get hour/minute/second but not both minute and second In[7]: df[B] = df[A].dt.components[hours] df Out[7]:A B0 02:00:00 2 1 01:00:00 1from this tim…

Understanding python numpy syntax to mask and filter array

Please help me understand how the lines below are working.How does a pair of parentheses create an array and then individual elements go through logical condition check and create a new array? How doe…