【问题标题】:Python looping list and append value to variablePython循环列表并将值附加到变量
【发布时间】:2022-07-06 21:23:02
【问题描述】:

我有一个带有 IP 的 .csv 文件,我用 Python 将其转换为列表:

def ip_list():
    iplist = []
    with open("/path/to/file") as csvfile:
        csvlist = csv.reader(csvfile)
        for lists in csvlist:
            for item in lists:
                iplist.append(item)
    return iplist

ip = ip_list()

print(ip)

>>> ["192.168.1.1", "192.168.1.2", ...]

现在我想获得列表中的每个值,并每次都将它们附加到给定的参数:

我想要:

#Example list for reproduction
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]

content = getcontent(ip[0-...])

我不想:

#Example list for reproduction
ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]

content1 = getcontent(ip[0])
content2 = getcontent(ip[1])
...

我想基本上每次都用一个新的 ip 值循环内容。

谢谢!

【问题讨论】:

  • 不要使用list作为变量名
  • 你还没有遇到过for循环或列表理解??

标签: python list loops csv indexing


【解决方案1】:

我不知道 getcontent() 函数的作用,但为什么不使用列表推导式遍历列表中的项目?

content = [getcontent(x) for x in ip]

【讨论】:

    【解决方案2】:

    您能否更具体地了解content = getcontent(ip[0-...])

    我不知道我是否得到你。 也许是这样的?

    ip = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
    def getip(li):
        for item in li:
            yield(item)
    
    ipgetter = getip(ip)
    print(next(ipgetter)) # 192.168.1.1
    print(next(ipgetter)) # 192.168.1.2
    

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 2019-04-13
      • 2021-10-31
      • 2015-08-23
      • 1970-01-01
      • 2016-08-01
      • 2019-05-15
      • 2022-01-10
      相关资源
      最近更新 更多