如何将嵌套字符串列表[['1.0\n'],['2.0\n'],['3.0\n']]转为无换行的整数1 2 3
实现方案
代码实现(Python)
可以通过嵌套遍历、字符串清理和类型转换完成需求,两种写法供参考:
简洁版(列表推导式)
original_list = [['1.0\n'], ['2.0\n'], ['3.0\n']] result = ' '.join(str(int(float(item[0].strip()))) for sublist in original_list for item in sublist) print(result) # 输出:1 2 3
分步版(易读性更高)
original_list = [['1.0\n'], ['2.0\n'], ['3.0\n']] processed_nums = [] # 遍历嵌套列表中的每个元素 for sublist in original_list: for s in sublist: # 1. 去除字符串中的换行符及空白字符 cleaned_str = s.strip() # 2. 转换为浮点数再转整数(自动舍弃小数部分) num = int(float(cleaned_str)) # 3. 转成字符串存入列表 processed_nums.append(str(num)) # 用空格连接所有字符串 result = ' '.join(processed_nums) print(result) # 输出:1 2 3
关键步骤说明
strip():彻底去除字符串两端的换行符\n、空格等空白字符,解决换行符残留问题- 类型转换:先转
float处理带小数的字符串,再转int得到整数结果 ' '.join():将处理后的整数字符串用空格连接,生成无逗号的目标格式
内容的提问来源于stack exchange,提问作者amslp
相关产品推荐
相关产品推荐

