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

如何创建单词或短语列表并随机选取元素赋值至变量?

创建列表并随机选取元素赋值给变量的实现方法

下面是几种主流编程语言的实现方式:

Python

  • 核心依赖内置的random模块,用choice()方法直接随机选列表元素
import random

# 定义包含单词/短语的列表
word_list = ["Hello World", "Python", "Stack Exchange", "随机选择"]

# 随机选取元素并赋值给变量
selected_item = random.choice(word_list)

print(selected_item)  # 打印结果验证

JavaScript(浏览器/Node.js通用)

  • 借助Math.random()生成随机索引,再从数组中取对应元素
// 创建单词/短语数组
const wordList = ["Hello World", "JavaScript", "Stack Exchange", "随机选择"];

// 计算随机索引并选取元素赋值
const selectedItem = wordList[Math.floor(Math.random() * wordList.length)];

console.log(selectedItem); // 打印结果验证

Java

方式一:用Random类生成随机索引

import java.util.Random;

public class RandomPick {
    public static void main(String[] args) {
        // 定义单词/短语数组
        String[] wordArray = {"Hello World", "Java", "Stack Exchange", "随机选择"};
        
        Random random = new Random();
        // 随机选取元素赋值
        String selectedItem = wordArray[random.nextInt(wordArray.length)];
        
        System.out.println(selectedItem); // 打印结果验证
    }
}

方式二:打乱列表后取首元素

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomPick {
    public static void main(String[] args) {
        List<String> wordList = new ArrayList<>();
        wordList.add("Hello World");
        wordList.add("Java");
        wordList.add("Stack Exchange");
        wordList.add("随机选择");
        
        // 打乱列表顺序
        Collections.shuffle(wordList);
        // 取第一个元素(已随机排序)
        String selectedItem = wordList.get(0);
        
        System.out.println(selectedItem); // 打印结果验证
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:45:28