python被游标坑了

为了方便,这次就不单独写脚本了,直接一步一步执行下来就好了
先说下游标,就是一个指针,比如我有
1
2
3
4
每条占一行,那么初始游标默认是在1的位置,当read(1)后,游标自动向下next,现在指在2的位置,依次类推,然后是3,4直到最后,除非强制移动游标,否则游标不会再返回的
今天写了一个脚本,具体就是有两个txt,a.txt和b.txt,从a.txt里面取值,去b.txt里面查看,是否存在,如果存在就把这条print出来
上例子

#先创建个a.txt
file_a = open('a.txt','w') #在当前目录下创建a.txt,写入模式,如果不确定目录先os.getcwd(),不然找不到不怪我哦
file_a.write('3\n9\n5\n4\n') #写入数据
file_a.close()
file_b = open('b.txt','w')
for i in range(10):
  file_b.write(str(i)+'\n') #写入1\n2\n3\n....9\n
file_b.close()

#下面来读取匹配下
file_a = open('a.txt','r')
file_b = open('b.txt','r')
for x in file_a:
  x = x.strip()
  for y in file_b:
    y = y.strip()
    if x == y:
      print x
      break
#结果是3\n9\n,只有3和9,这下懵逼了,应该是3\n9\n5\n4\n啊
file_a.close()
file_b.close()

#结果这破玩意我改了一个小时,怎么都是3,然后觉得这样没有啥效果,仔细想了一下,原来是游标的问题,尼玛的
#我来解释下,因为file_a的类型是file,而file类型是使用指针的,就是和我上面说的一样,除非强制移动,否则游标不会再返回的
#就是说在嵌套循环里面for y in file_b的时候匹配到3了,那么游标停在3上,下一个是9,那么第二轮是从3开始向下找,找到9,9之后就再没有了,所以无论怎么匹配也匹配不到的
#知道原因在哪里就好办了,有两种办法,先说第一种把,用seek(0)将游标移动到开始
file_a = open('a.txt','r')
file_b = open('b.txt','r')
for x in file_a:
  x = x.strip()
  for y in file_b:
    y = y.strip()
    if x == y:
      print x
      file_b.seek(0)
      break
file_a.close()
file_b.close()


#第二种是用readlines,把文件里的数据按行read成list,list是没有游标概念的,list只有下标,每次都会从头循环
file_a = open('a.txt','r')
file_b = open('b.txt','r')
file_b_list = file_b.readlines() #只改file_b就可以了,因为a是主表
for x in file_a:
  x = x.strip()
  for y in file_b_list:
    y = y.strip()
    if x == y:
      print x
      break
file_a.close()
file_b.close()
#我建议用第二种,因为第一种需要有游标重置的动作,虽然几条没有影响,不过如果是几千万的话影响应该会很大把,不过话说回来了,几千万谁还会用嵌套循环呢,hash或二分法才是正确的选择,当然最快的一定是树查询

 

转载于:https://www.cnblogs.com/xiu123/p/8433878.html

### Python 中 Plot 游标的使用 在 Python 的数据可视化领域,`matplotlib` 是最常用的绘图库之一。通过 `matplotlib` 提供的功能,可以实现交互式的游标(cursor),以便用户能够更方便地探索图表中的细节。 以下是关于如何在 Python 中使用 Plot 游标的详细介绍: #### 使用 Matplotlib 实现游标功能 Matplotlib 提供了一个名为 `Cursor` 的工具类,位于模块 `mpl_toolkits.axes_grid1` 下。该类允许开发者向二维坐标系添加十字光标效果[^4]。下面是一个简单的例子展示如何启用游标功能: ```python import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1 import Cursor fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30]) # 绘制简单折线图 # 启用游标 cursor = Cursor(ax, useblit=True, color='red', linewidth=1) plt.show() ``` 上述代码创建了一条基本的折线图,并启用了红色的十字光标。当鼠标移动到图像上时,会显示动态更新的十字形状[^4]。 #### 更高级的交互方式——Data Cursor 如果希望进一步增强用户体验,可以通过自定义事件监听器来实现更加复杂的交互逻辑。例如,点击某个点后弹出其具体数值信息。这种功能通常被称为 **data cursor** 或者 **annotation box**。 以下是一段演示如何实现 data cursor 功能的代码片段: ```python import numpy as np import matplotlib.pyplot as plt class DataCursor(object): def __init__(self, artist, formatter="{x:.2f}, {y:.2f}", offsets=(-20, 20), **kwargs): self._figure, self._axes, self._line = None, None, None self._labels = [] self._text_template = formatter self._offsets = offsets self._dropped = False if isinstance(artist, list): self._artists = artist elif hasattr(artist, '__iter__'): self._artists = list(artist) else: self._artists = [artist] for a in self._artists: fig = a.figure axes = a.axes x,y = a.get_data() label = "{:g},{:g}".format(x[0], y[0]) ann = axes.annotate(label, xy=(x[0], y[0]), ha="right", va="bottom", bbox=dict(boxstyle="round,pad=0.3", edgecolor="black"), visible=False) self._labels.append(ann) fig.canvas.mpl_connect('motion_notify_event', self) def __call__(self, event): for i,a in enumerate(self._artists): cont, ind = a.contains(event) if cont and not self._dropped: x,y = a.get_data() index = ind["ind"][0] template = self._text_template.format(x=x[index], y=y[index]) self._labels[i].set_text(template) self._labels[i].set_position((event.xdata+self._offsets[0], event.ydata+self._offsets[1])) self._labels[i].set_visible(True) else: self._labels[i].set_visible(False) event.canvas.draw_idle() t = np.arange(0., 5., 0.01) s = np.sin(2*np.pi*t) fig, ax = plt.subplots() line, = ax.plot(t,s,'-b') dcursor = DataCursor(line) plt.show() ``` 此脚本实现了这样一个特性:每当用户的鼠标悬停在一个特定的数据点上方时,就会显示出这个点的具体位置坐标值[^5]。 #### 总结 无论是基础版还是加强版的游标应用,在实际项目开发过程中都可以极大地提升最终产品的易用性和美观度。以上就是有关于 Python plot cursor usage 的全部内容介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值