【问题标题】:genereting list from file python从文件python生成列表
【发布时间】:2016-03-20 01:08:34
【问题描述】:

我有一个看起来像这样的文件:完全一样

Pokemon     HP  Attack_Points   Type    Weakness
Bulbasaur   45     49     Grass Fire
Ivysaur     60     62     Grass Fire
Venusaur    80     82     Grass Fire

我正在尝试从随机行生成列表,这是我的代码:

from random import randint

open_pokedex=open("pokedex.txt","r")
p1_p1=list()
pokemon_selection=(randint(1,40))
p1_p1.append(open_pokedex.readline()[pokemon_selection])

但这不起作用有人有什么想法吗? 输出:这次它生成 31 并将 p1_p1 显示为 this = ['\t']

问题解决了

但是 bcs 的坏 txt 文件会这样做 ['Charmander \t39\t52\tFire\tWater\n'] 如何在不弄乱文件本身的情况下擦除这些选项卡

【问题讨论】:

  • 您可能想要readlines() 而不是readline()。您现在应该向我们展示您的代码的作用/输出,以便我们获得更多信息。说“它不起作用”是没有用的,因为我们需要知道它在什么方面不起作用。
  • 是的,你是对的,让我更改编辑:完成

标签: python list file random


【解决方案1】:

使用linecache.getline。它完全符合您的要求;从文件中获取行lineno

import linecache
from random import randint

pokemon_selection = randint(1, 40)
pokemon = linecache.getline("pokedex.txt", pokemon_selection)

【讨论】:

  • 好吧,我想将它们添加到列表中并将您的代码更改为此 p1_p1.linecache.getline("pokedex.txt", pokemon_selection) 它说 AttributeError: 'list' object has no attribute 'linecache '
  • @CiocomoTrombetta,然后,p1_p1.append(pokemon)`
  • @CiocomoTrombetta,顺便说一句,如果可能,请发布另一个问题,而不是更新问题。
  • @CiocomoTrombetta, str.strip 删除前导、尾随空格(包括空格、制表符、垂直制表符、换行符)。但不在中间。
  • @CiocomoTrombetta,你想要的是str.splitp1_p1.append(linecache.getline("pokedex.txt", pokemon_selection).split())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多