Python:打印不带括号和单引号的列表吗? [英] Python: Printing a list without the brackets and single quotes?

查看:166
本文介绍了Python:打印不带括号和单引号的列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完整的IP地址列表.我想遍历列表并打印每个IP地址.当我尝试这样做时:

I have a list full of IP addresses. I would like to iterate through the list and print each IP address. When I try doing this:

def printList(theList):
    for item in theList:
        print item

输出看起来像这样:

['8.0.226.5']
['8.0.247.5']
['8.0.247.71']
['8.0.249.28']
['8.0.249.29']

我已经尝试了所有方法,包括循环中的"print item [0]".我在做什么错了?

I have tried everything, including "print item[0]" in the loop. What am I doing wrong?

推荐答案

列表中的每个项目本身就是一个单例列表.大概没有理由-如果您无法命名,请删除它们(通过在re.findall上使用re.find或从re.findall返回的列表中返回单个项目),它们只是多余的,并且在这种情况下会引起麻烦.

Each item in the list is itself a singleton list. There's propably no reason for this - if you can't name one, go and remove them (by using re.find over re.findall or returning a single item from the list returned by re.findall), they're just redundant and cause trouble like in this case.

无论如何,print item[0]都应该在打印列表中的单个元素时起作用,并且与列表的str()不同,它不会先通过repr运行项目(这会导致引号,并且会逃脱无法打印的内容)字符(如果字符串中有字符).一旦摆脱了多余的单例列表,print '\n'.join(items)也将起作用.

Regardless, print item[0] should work as it's printing the single element in the list, and unlike the str() of lists, it won't run the item through repr first (which causes the quotes and would escape unprintable characters if there were any in the string). And once you got rid of the redundant singleton lists, print '\n'.join(items) will work as well.

如果theList中有一个空列表,则您的代码将引发错误.如果recentFile中的一行不包含任何格式如IP的内容,则returnIP将返回一个空列表,而comparisonFile中的任何一行都将返回(顺便说一句:使用描述性名称打开它)一开始,但是一次又一次地打开它而在chechMatch中也没有描述性名称)也不包含IP地址,您将获得另一个空列表,该列表当然等于作为参数ip传递的空列表.因此,对于recentFile中的非IP名称,将添加空列表.如果从returnIP返回字符串而不是单例列表,在当前行中没有IP时使用None,并且如果returnIP返回compareFiles中的检查/添加,可以避免整个麻烦>.

Your code throws an error if there is an empty list in theList. If there is a line in recentFile that does not contain anything formatted like an IP, an empty list will be returned by returnIP, and if any line in comparisonFile (by the way: you open it with a descriptive name at the beginning, but open it again and again without a descriptive name in chechMatch) contains no IP address either, you'll get another empty list which of course equals the empty list passed as parameter ip. So for non-IP names in recentFile, empty lists will be added. This whole troubel can be avoided if you return strings instead of singleton lists from returnIP, use None when there is no IP in the current line, and skip the checking/appending in compareFiles if returnIP returns None.

这篇关于Python:打印不带括号和单引号的列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆