You need to enable JavaScript to run this app. Python for循环写入CSV时如何新增随机城市字符串location列
优惠活动
大模型
产品
解决方案
定价
更多

Python for循环写入CSV时如何新增随机城市字符串location列

新增随机location列的CSV写入实现

核心改动步骤

  • 整理可选城市名作为固定取值池,存入Python列表
  • 修改CSV表头行,在原有列名末尾追加location字段
  • 在逐行写入的for循环迭代中,每次从城市池随机抽取一个值,补充到当前行的写入字段列表末尾

调整后可直接运行的代码

import random

# 自定义location可选值,可按需添加更多城市名
city_pool = ["Amsterdam", "London", "Paris"]

with open(output_file_path, 'w') as csvfile: 
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    # 更新表头,新增location列
    csv_writer.writerow(['timestamp', 'id', 'integercolumn1', 'integercolumn2', 'location'])

    for i in range(100):
        # 循环内随机选取城市作为当前行的location值
        current_location = random.choice(city_pool)
        csv_writer.writerow([
            timestamp, 
            'demo-{}'.format(i), 
            random.randint(0, 75), 
            random.randint(4, 10),
            current_location
        ])

生成效果示例

调整后输出的CSV完全匹配要求的结构:

timestamp,id,integercolumn1,integercolumn2,location
2020-1,demo-0,32,25,London
2020-1,demo-1,45,14,Paris
2020-1,demo-2,17,9,Amsterdam

实用技巧:如果需要调整不同城市的出现概率,只需要在city_pool列表中重复加入对应城市名即可,比如把"London"写两次,London被随机选中的概率就会翻倍,不需要额外写随机逻辑分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 20:36:08