我在列表中有列名称,我想将值1分配给这些列名称,并将值0分配给其余列。 例如。
perms_name = ['name','place','thing']
最初CSV如下:
name,age,place,thing,phone_no
我想使csv看起来像这样:
name,age,place,thing,phone_no
1,0,1,1,0
我可以通过这个简单地做到这一点
with open('eggs.csv','a') as csvfile:
fieldname = ["name","age","place","thing","phone_no"]
writer = csv.DictWriter(csvfile,fieldnames=fieldname)
writer.writeheader()
writer.writerow(
{'name': 1,'age':0,'place':1,'thing':1,'phone_no':0}
)
但是它们是任何更快的方法,在这种情况下,它们只有5列,如果它们是100列,而我只想为列表中提到的列分配1。
答案 0 :(得分:1)
您可以通过RewriteEngine off
RewriteEngine on
AddDefaultCharset utf-8
#Alter the default time zone for the site
SetEnv TZ Europe/London
#set the RewriteBase
RewriteBase /
#Redirect from root to home.php
RewriteCond %{REQUEST_URI} ^\/?$
RewriteRule (\/)?$ home.php [L]
#Redirect from /subdir to /subdir/home.php
RewriteCond %{REQUEST_URI} ^/subdir\/?$
RewriteRule ^subdir(\/)?$ subdir/home.php [L]
#Removing .php from the end of file paths
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L,QSA]
#Forcing https://
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI}
#Redirect to 404 error page
ErrorDocument 404 /page_not_found.php
RewriteCond %{HTTP_HOST} ^(www\.)?example.com/(.*)$
RewriteRule ^$ "https://example.com/page_not_found.php" [R=301]
运算符在Python 3中在线解压缩字典。与**
结合使用,无需为每个字段明确写出键和值:
dict.fromkeys
一次定义字典,然后使用:
perms_name = ['name','place','thing']
fieldname = ['name', 'age', 'place', 'thing', 'phone_no']
d = {**dict.fromkeys(fieldname, 0), **dict.fromkeys(perms_name, 1)}
{'age': 0, 'name': 1, 'phone_no': 0, 'place': 1, 'thing': 1}
答案 1 :(得分:1)
除了jpp的答案,您还可以使用稍微令人困惑的列表理解来构建字典。
perms_name = ['name','place','thing']
fieldname = ['name', 'age', 'place', 'thing', 'phone_no']
d = {field : (1 if field in perms_name else 0) for field in fieldname}
# {'name': 1, 'age': 0, 'place': 1, 'thing': 1, 'phone_no': 0}
如果有任意数量的列可以从csv中读取它们,而不是将其硬编码到脚本中,那么这也许也是值得的。