【问题标题】:How to remove a word from a list with a specific character in a specific index position如何从特定索引位置具有特定字符的列表中删除单词
【发布时间】:2022-12-08 04:38:01
【问题描述】:

这是我到目前为止所拥有的:

wlist = [word for word in wlist if not any(map(lambda x: x in word, 'c'))]

此代码有效,但在其当前状态下,它将从 wlist 中删除所有包含“c”的字符串。我希望能够指定一个索引位置。例如,如果

wlist = ['snake', 'cat', 'shock']
wlist = [word for word in wlist if not any(map(lambda x: x in word, 'c'))]

并且我选择索引位置 3,因为 'shock' 是索引 3 中唯一带有 c 的字符串,因此只会删除 'shock'。当前代码将同时删除 'cat' 和 'shock'。我不知道如何整合这个,我会很感激任何帮助,谢谢。

【问题讨论】:

    标签: python string list


    【解决方案1】:

    只需使用切片:

    out = [w for w in wlist if w[3:4] != 'c'] 
    

    输出:['snake', 'cat']

    【讨论】:

    • 检查多个索引怎么样?
    • @I'mahdi OP 要求提供单一索引 (3)
    • @I'mahdi 使用多个切片?
    • @PranavHosangadi,是的,我知道,但这非常简单,我认为不能用于复杂的问题。我的解决方案只能在 [3, 7, 10, 20] 中使用,但是用这个?!例如,如果 op 想要索引 3, 7, 10, 20, ...
    • @I'mahdi 为什么不呢? positions = [0, 3] ; [w for w in wlist if all(w[i:i+1] != 'c' for i in positions)]
    【解决方案2】:

    也许你应该使用正则表达式。我怎么不知道他们)),所以只是遍历单词列表。

    for i in wlist:
    try:
        if i[3] == 'c':
            wlist.remove(i)
    except IndexError:
        continue
    

    【讨论】:

    • 遍历列表时不要从列表中删除
    • @PranavHosangadi 是的,你是对的,有时我只是实施想到的第一个解决方案而不考虑,抱歉。
    【解决方案3】:

    首先,你需要检查'c'在word中是否存在,然后检查索引。

    wlist = ['snake', 'cat', 'shock']
    result = [w for w in wlist if not ('c' in w and w.index('c') == 3)]
    # ---------------------with this : ^^^^^^^^ if 'c' does not exist in word, we don't need to check the index and don't get any error.
    # for checking for multiple index:
    # result = [w for w in wlist if not ('c' in w and w.index('c') in [3, 7, 10])]
    print(result)
    # ['snake', 'cat']
    

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 2019-01-11
      相关资源
      最近更新 更多