python - python切片,一行复制使用后前进n行

标签 python list slice

我正在编写脚本,请看这里:

from pysnap import Snapchat
import time

usnlist = raw_input('Enter file name: ')

s = Snapchat()

def filter(username, password):
    s.login(username, password)
    with open (usnlist, 'r') as file:
        for line in file:
            ok = False
            while not ok:
                try:
                    resp = s.add_friend(line.rstrip("\n"))
                    if 'object' in resp.keys():
                        # 'object' is contained within resp as a key
                        if resp['object']['type']:
                            # type is 1
                            with open ('private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: FRIENDS"
                        else:
                            # type is 0
                            with open ('n-private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: EVERYONE"
                        s.delete_friend(line)
                    else:
                        # no object in resp, so it's an invalid username
                        print line.rstrip("\n") + " is not a valid username"
                    ok = True
                except:
                    time.sleep(5)
                    print "SNAPCHAT SERVER OVERLOAD - HOLD ON."

username = raw_input('Enter username: ')
password = raw_input('Enter password: ')

filter(username, password)

我现在想要的是能够输入一个值让我们称之为n 当我输入 n 时,机器人只会抓取每一 n 行。

例如。 N = 2。 该机器人现在仅从列表中每隔一个用户名抓取并输入一次。

我想到了一些东西,比如将 [0::2] 添加到:resp = s.add_friend(line.rstrip("\n")) 结果:resp = s.add_friend(line[0::2].rstrip("\n"))

但这没有用,机器人直接打印“SNAPCHAT SERVER OVERLOAD - HOLD ON。” 不检查任何名称。

我的想法是:

http://stackoverflow.com/questions/18155682/gathering-every-other-string-from-list-line-from-file

但所提供的信息不足以让我让它发挥作用。 我用的是python 2.7.8

我希望有一种方法可以告诉 python:“获取文件中的每一行 n” 因为这基本上就是我要找的东西。

如果有人能提供帮助那就太好了!

最佳答案

你尝试的是分割行,而不是文件。文件不支持切片,但 itertools模块有一个切片任意迭代的函数:

import itertools
for line in itertools.islice(file, None, None, n):
    do_whatever_with(line)

前两个参数是开始和停止;这些参数的 None 值表示输入的开始和结束,因为您不能像在常规切片中那样省略它们。第三个参数是步骤。

关于python - python切片,一行复制使用后前进n行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27452201/

相关文章:

python - 如何像在 R 中那样在 Python 中绘制 CART 树?

python - 在 termux 中运行具有依赖项的 python 应用程序

python - 使用 scikit-learn 重新初始化学习到的线性模型

python - 如何检测列表中的非数字?

python - 如何在 TensorFlow 中切片数据集?

go - 如何查找两个 slice 是否引用同一内存?

javascript - 对包含对象的数组进行切片并获取包含对象副本的数组

Python-密码库

mysql - mysql中的优先级

list - 如何将 json 映射转换为列表字符串?