社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python列表中只替换以某个字母开头的文本?

AAKASH IYER • 5 年前 • 1554 次点击  

我的问题与 excel formula to replace or stubstitute only text that starts with a certain letter 但我需要一个python代码。我正在尝试嵌套if,但它只替换第一个字符,而不是整个元素。

元素也是字母数字的

List= ['F43.9', 'F53.2', 'H10.9', 'H60.9', 
       'S83.6', 'S01.88', 'J18.9', 'K35.9', 'S42.20', 'J06.9'....]

所以我想要的结果是:

list=['qwe'、'qwe'、'equal'、'equal'、'chronic'、'chronic'、'responsible'、'priority'、'chronic'、'responsible'、…]

我需要用 F 例如 F43.9,F53.2,etc . 具有 "qwe" . 对于不同的字母也一样。列表中有30000个元素,具有600个唯一值。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44049
 
1554 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Jonas
Reply   •   1 楼
Jonas    6 年前

试试这个:

for i in range(0, len(list)):
    if list[i].startswith('F'):
        list[i] = 'qwe'
    elif list[i].startswith('H'):
        list[i] = 'chronic'
    elif list[i].startswith('S'):
        list[i] = 'liable'
    else list[i].startswith('J'):
        list[i] = 'priority'

等。。。

hemanta
Reply   •   2 楼
hemanta    6 年前

通过使用列表理解,我们可以做到这一点:

new_list = ['qwe' + List[i][1:] if List[i].startswith('F') else List[i] for i in range(len(List)) ]
print(new_list)
['qwe43.9','qwe53.2','H10.9','H60.9', 'S83.6','S01.88','J18.9','K35.9','S42.20',
'J06.9']

您可以将字母“f”替换为要替换起始字母的字符串中的任何其他字母。

AkshayNevrekar FilipShark
Reply   •   3 楼
AkshayNevrekar FilipShark    6 年前

可以使用 list-comprehension 为了它

List = ['qwe'+i[1:] if i.startswith('F') else i for i in List]
typedef struct James
Reply   •   4 楼
typedef struct James    6 年前

新编辑表示要替换整个单词。只需检查元素 startswith() 所需的字符,然后将其替换为所需的字符串。这会变得有点健壮,所以你可以用字典更好。


for i in range(0, len(list)):
    if list[i].startswith('F'):
        list[i] = 'qwe'
    elif list[i].startswith('H'):
        list[i] = 'equals'
    elif list[i].startswith('S'):
        list[i] = 'chronic'

map = {
    'F': 'qwe',
    'H': 'equals'
    'S': 'chronic'
     # etc etc
}

for i in range(0, len(list)):
    if list[i][0] in map.keys():    # check if first char is a key in map
        list[i] = map[list[i][0]]   # if it is, replace list[i] with the value in map