python 二维数组元素返回二维坐标_python – 从二维数组中返回生成器而不是位置列表...

我昨天正在进行一场游戏,我必须遍历一个二维阵列并找到标记为“d”的任何单元格的位置(其中单元格表示为“ – ”表示空白,“d”表示为脏).

我使用两个for循环做到了这一点:

def find_dirty_cells(board):

dirty_cells = []

for enum, row in enumerate(board):

for enumrow, cell in enumerate(row):

if cell == 'd':

dirty_cells.append((enum, enumrow))

return dirty_cells

但后来我认为构建一个生成器对象并返回它可能会更好,所以我写了这个:

def find_dirty_cells(board):

return ((enum, enumrow) for enumrow, cell in enumerate(row) for enum, row in enumerate(board) if cell == 'd')

但第二个给出了不正确的数据响应(即,它没有找到’d’单元格).必须有一些简单的东西,我忽略了第二个不等于第一个,但我看不到它.我试图解决的真正问题是:有一种简单的方法让我的第一次尝试返回发电机吗?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用神经网络来进行二维坐标分类的任务。下面是一个使用Python和TensorFlow库实现的简单示例代码: ```python import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 生成示例数据 num_points = 1000 vectors_set = [] for i in range(num_points): x = np.random.normal(0.0, 0.55) y = x * 0.1 + 0.3 + np.random.normal(0.0, 0.03) vectors_set.append([x, y]) # 将数据分为两类,并进行one-hot编码 labels = [[1, 0] if x < y else [0, 1] for x, y in vectors_set] # 将数据转换为NumPy数组 data = np.array(vectors_set) labels = np.array(labels) # 创建神经网络模型 input_dim = 2 output_dim = 2 X = tf.placeholder(tf.float32, shape=[None, input_dim]) Y = tf.placeholder(tf.float32, shape=[None, output_dim]) W = tf.Variable(tf.zeros([input_dim, output_dim])) b = tf.Variable(tf.zeros([output_dim])) output = tf.nn.softmax(tf.matmul(X, W) + b) # 定义损失函数和优化器 loss = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(output), axis=1)) optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(loss) # 训练模型 sess = tf.Session() sess.run(tf.global_variables_initializer()) for step in range(1000): sess.run(optimizer, feed_dict={X: data, Y: labels}) # 可视化分类结果 W_val, b_val = sess.run([W, b]) x = np.linspace(-2, 2, 100) y = -W_val[0][0] / W_val[1][0] * x - b_val[0] / W_val[1][0] plt.plot(x, y, 'r', label='Decision Boundary') plt.scatter(data[:, 0], data[:, 1], c=np.argmax(labels, axis=1), alpha=0.4) plt.legend() plt.show() sess.close() ``` 这个示例代码使用了一个简单的线性分类器,可以将二维坐标点分为两类。你可以根据实际需求调整模型的结构和参数。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值