这个操作涉及三种数据结构之间的转换:
这种转换在以下场景中很有用:
# 原始列表
word_list = ['hello', 'world']
# 列表转字符串
combined_string = ' '.join(word_list) # 使用空格连接
print(combined_string) # 输出: "hello world"
# 字符串转字符列表
letter_list = list(combined_string.replace(' ', '')) # 移除空格后转换为字符列表
print(letter_list) # 输出: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
# 更详细的版本(保留空格作为字符)
detailed_letter_list = list(combined_string)
print(detailed_letter_list) # 输出: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
const wordList = ['hello', 'world'];
const combinedString = wordList.join(' ');
const letterList = combinedString.replace(/\s/g, '').split('');
console.log(letterList); // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> wordList = Arrays.asList("hello", "world");
String combinedString = String.join(" ", wordList);
List<Character> letterList = new ArrayList<>();
for (char c : combinedString.replace(" ", "").toCharArray()) {
letterList.add(c);
}
System.out.println(letterList);
}
}
from collections import Counter
word_list = ['hello', 'world']
letter_freq = Counter(''.join(word_list))
print(letter_freq) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
def letters_from_words(words):
for word in words:
yield from word
# 使用
big_word_list = ['very', 'long', 'list', 'of', 'words']
for letter in letters_from_words(big_word_list):
process_letter(letter) # 处理每个字母
没有搜到相关的文章