[英]list comprehension over tuple of tuple
I have the following string我有以下字符串
conf=(("X", "X", "-"), ("O", "O", "-"), ("X", "X", "O")) conf=(("X", "X", "-"), ("O", "O", "-"), ("X", "X", "O"))
which is a tuple of tuple, I want to iterate over each element and find the "-" which means the empty space and return a tuple with the coordinate of the "-"这是一个元组的元组,我想遍历每个元素并找到“-”,这意味着空白空间并返回一个带有“-”坐标的元组
What I have tried so far, which does not work到目前为止我尝试过的方法不起作用
conf=(("X", "X", "-"), ("O", "O", "-"), ("X", "X", "O"))
free_spaces = ((i,j) for i,j in range(3) if conf[i][j] == "-" )
free_spaces = {(x,y) for x in conf for y in conf if conf[x][y] == "-" }
can someone help with this one?有人可以帮忙吗?
Tweak your code a little and you will have your solution:稍微调整一下你的代码,你就会得到你的解决方案:
[(i,j) for i in range(len(conf)) for j in range(len(conf[i])) if conf[i][j]=='-' ]
If you are sure about the length of your tuple being 3 every time, you can skip the len()
如果你确定你的元组的长度每次都是 3,你可以跳过
len()
Returning -1 if "-" not in tuple;如果“-”不在元组中,则返回 -1; otherwise returning index.
否则返回索引。
conf=(("X", "X", "-"), ("O", "O", "-"), ("X", "X", "O"))
print([conf[i].index("-") if "-" in conf[i] else -1 for i in range(len(conf))])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.