使用字符串列表创建表

时间:2018-11-18 04:02:58

标签: python-3.x list

我需要将字符串列表转换成三列表,其中第一列比最长的字符串长1个空格。我已经弄清楚了如何识别最长的字符串以及它的长度,但是要使表格形成表格是非常棘手的。这是其中包含列表的程序,它向您显示最长的一个程序是26个字符。

def main():
    mycities = [['Cape Girardeau', 'MO', '63780'], ['Columbia', 'MO', '65201'], 
                ['Kansas City', 'MO', '64108'], ['Rolla', 'MO', '65402'], 
                ['Springfield', 'MO', '65897'], ['St Joseph', 'MO', '64504'], 
                ['St Louis', 'MO', '63111'], ['Ames', 'IA', '50010'], ['Enid', 
                'OK', '73773'], ['West Palm Beach', 'FL', '33412'],
                ['International Falls', 'MN', '56649'], ['Frostbite Falls', 
                'MN', '56650']]

    col_width = max(len(item) for sub in mycities for item in sub)
    print(col_width)


main()

现在我只需要像这样打印它即可

Cape Girardeau      MO 63780
Columbia            MO 65201
Kansas City         MO 64108
Springfield         MO 65897
St Joseph           MO 64504
St Louis            MO 63111
Ames                IA 50010
Enid                OK 73773
West Palm Beach     FL 33412
International Falls MN 56649
Frostbite Falls     MN 56650

3 个答案:

答案 0 :(得分:0)

“字符串名称” .ljust(26)将在字符串末尾添加空格。例如,

Ames.ljust(26)将导致“ Ames(此处为22个空格)”,然后将打印下一列。如果不确定最长的城市是多少,可以在按长度排序列表中的城市后,用len(cities [-1])替换26个城市。为此,您可以执行sortedCities = sorted(cityListVariable,key = len)

答案 1 :(得分:0)

您走到了正确的起点-例如,鉴于您拥有的列表的特定结构,您可以使用计算出的col_width来确定名称后所需的空格数每个城市的名称,并附加到每个城市名称的末尾:

for city in mycities:
    # append the string with the number of spaces required
    city_padded = city[0] + " " + " "*(col_width-len(city[0]))
    print(city_padded + city[1] + " " + city[2])

以您的示例为例,这将产生:

Cape Girardeau      MO 63780
Columbia            MO 65201
Kansas City         MO 64108
Rolla               MO 65402
Springfield         MO 65897
St Joseph           MO 64504
St Louis            MO 63111
Ames                IA 50010
Enid                OK 73773
West Palm Beach     FL 33412
International Falls MN 56649
Frostbite Falls     MN 56650

请注意,在您问题的原始版本中,您在mycities变量的子列表中缺少逗号(我已在其中添加了编辑内容)。

请注意,Python中的惯例是,为了便于阅读,在变量名中用下划线将单词隔开,因此您可以将mycities重命名为my_cities

pep8参考:(https://www.python.org/dev/peps/pep-0008/#function-and-variable-names

答案 2 :(得分:0)

class Animal {
  constructor(isAgressive) {
    this.seesMe = isAgressive ? this.attack : this.flee;
  }
  
  attack = function () {
    console.log('attack!');
  }
  
  flee() {
    console.log('cya!');
  }
}

const zebra = new Animal(false);
const lion = new Animal(true);

zebra.seesMe();
lion.seesMe();