You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将列表中的大小写单词分别存入不同列表?

Corrected Solution

First, let's fix the core issues in your original code:

  • You converted a list to a string when applying regex, leading to matches on brackets/quotes instead of actual words.
  • Your nested list structure made processing needlessly complex.
  • The lowercase check compared a string to a boolean, which is always False.

Here's the revised code to achieve your desired result:

import re

# Input string
input_str = 'ArvindBholaGujarat...creativedirectorSubhashGhai...director'

# Split the string into segments using '...' as the delimiter
segments = input_str.split('...')

# Initialize empty lists for results
capitalized_words = []
lowercase_words = []

# Regex pattern to extract:
# - All lowercase words: [a-z]+
# - CamelCase/words with uppercase letters: [A-Z][a-zA-Z]*
extraction_pattern = r'[a-z]+|[A-Z][a-zA-Z]*'

for segment in segments:
    # Extract all valid words from the current segment
    words = re.findall(extraction_pattern, segment)
    for word in words:
        # Classify each word based on presence of uppercase characters
        if any(char.isupper() for char in word):
            capitalized_words.append(word)
        else:
            lowercase_words.append(word)

# Output the final lists
print("含大写字母的单词列表:", capitalized_words)
print("全小写单词列表:", lowercase_words)

Expected Output:

含大写字母的单词列表: ['ArvindBholaGujarat', 'SubhashGhai']
全小写单词列表: ['creativedirector', 'director']

Key Improvements:

  • Direct string processing: We avoid nested lists and work directly with split string segments.
  • Targeted regex: The pattern correctly separates lowercase words from words containing uppercase letters (including camelCase).
  • Accurate classification: Using any(char.isupper() for char in word) reliably identifies words with uppercase characters.

内容的提问来源于stack exchange,提问作者Barira Ushshaque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:43:03